108、将有序数组转换为二叉搜索树
将一个按照升序排列的有序数组,转换为一棵高度平衡二叉搜索树。
本题中,一个高度平衡二叉树是指一个二叉树每个节点 的左右两个子树的高度差的绝对值不超过 1。
示例:
给定有序数组: [-10,-3,0,5,9],
一个可能的答案是:[0,-3,9,-10,null,5],它可以表示下面这个高度平衡二叉搜索树:
0
/ \
-3 9
/ /
-10 5
链接:https://leetcode-cn.com/problems/convert-sorted-array-to-binary-search-tree
题解
利用有序数组,递归构建。
1、中序遍历:始终选择中间位置左边元素作为根节点
class Solution {
int[] nums;
// 递归构建
public TreeNode helper(int left, int right) {
if (left > right) return null;
// always choose left middle node as a root 始终选择左边
int p = (left + right) / 2;
// inorder traversal: left -> node -> right
TreeNode root = new TreeNode(nums[p]);
root.left = helper(left, p - 1);
root.right = helper(p + 1, right);
return root;
}
public TreeNode sortedArrayToBST(int[] nums) {
this.nums = nums;
return helper(0, nums.length - 1);
}
}
// 链接:https://leetcode-cn.com/problems/convert-sorted-array-to-binary-search-tree/solution/jiang-you-xu-shu-zu-zhuan-huan-wei-er-cha-sou-s-15/
- kotlin实现
/**
* Example:
* var ti = TreeNode(5)
* var v = ti.`val`
* Definition for a binary tree node.
* class TreeNode(var `val`: Int) {
* var left: TreeNode? = null
* var right: TreeNode? = null
* }
*/
class Solution {
fun sortedArrayToBST(nums: IntArray): TreeNode? {
return toTree(nums, 0, nums.size - 1)
}
fun toTree(nums: IntArray, start: Int, end: Int): TreeNode? {
if (start > end) return null
val mid = (start + end) / 2
return TreeNode(nums[mid]).apply {
left = toTree(nums, start, mid - 1)
right = toTree(nums, mid + 1, end)
}
}
}
2、中序遍历:始终选择中间位置右边元素作为根节点
class Solution {
int[] nums;
public TreeNode helper(int left, int right) {
if (left > right) return null;
// always choose right middle node as a root 始终选择右边
int p = (left + right) / 2;
if ((left + right) % 2 == 1) ++p;
// inorder traversal: left -> node -> right
TreeNode root = new TreeNode(nums[p]);
root.left = helper(left, p - 1);
root.right = helper(p + 1, right);
return root;
}
public TreeNode sortedArrayToBST(int[] nums) {
this.nums = nums;
return helper(0, nums.length - 1);
}
}
// 链接:https://leetcode-cn.com/problems/convert-sorted-array-to-binary-search-tree/solution/jiang-you-xu-shu-zu-zhuan-huan-wei-er-cha-sou-s-15/
3、中序遍历:选择任意一个中间位置元素作为根节点
class Solution {
int[] nums;
Random rand = new Random();
public TreeNode helper(int left, int right) {
if (left > right) return null;
// choose random middle node as a root 随机左右
int p = (left + right) / 2;
if ((left + right) % 2 == 1) p += rand.nextInt(2);
// inorder traversal: left -> node -> right
TreeNode root = new TreeNode(nums[p]);
root.left = helper(left, p - 1);
root.right = helper(p + 1, right);
return root;
}
public TreeNode sortedArrayToBST(int[] nums) {
this.nums = nums;
return helper(0, nums.length - 1);
}
}
// 链接:https://leetcode-cn.com/problems/convert-sorted-array-to-binary-search-tree/solution/jiang-you-xu-shu-zu-zhuan-huan-wei-er-cha-sou-s-15/
转载请注明来源,欢迎对文章中的引用来源进行考证,欢迎指出任何有错误或不够清晰的表达。可以在下面评论区评论,也可以邮件至 1056615746@qq.com