Given an array where elements are sorted in ascending order, convert it to a height balanced BST.
For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1.
Example:
Given the sorted array: [-10,-3,0,5,9], One possible answer is: [0,-3,9,-10,null,5], which represents the following height balanced BST: 0 / -3 9 / / -10 5
- 中间的index不是除以2,而是mid = low + (high - low) / 2;
-
初始化节点: TreeNode node = new TreeNode(0);
和改变节点:node = helper(nums, 0, nums.length - 1);
是两个步骤的时候,就要用helper函数 - 好吧,原来高度不超过1是通过index来控制的,也是把左右当做参数:左边一个右边一个
node.left =
node.right =
都是在helper中完成的,helper可以多功能一些
helper中也有边界条件
而且用了数组的话,函数的参数最好带上数组名
自己写的,不知道里面为啥会链表有环
class Solution {
public TreeNode sortedArrayToBST(int[] nums) {
//特殊情况
if (nums.length < 0 || nums == null)
return null;
TreeNode root = new TreeNode(0);
return helper(root, nums, 0, nums.length - 1);
}
TreeNode helper(TreeNode node, int[] nums, int left, int right) {
//特殊情况
if (left > right) {
return null;
}
int mid = left + (right - left) / 2;
node.left = helper(node, nums, left, mid - 1);
node.right = helper(node, nums, mid + 1, right);
return node;
}
}
正确版本
class Solution {
public TreeNode sortedArrayToBST(int[] nums) {
//特殊情况
if (nums.length < 0 || nums == null)
return null;
TreeNode root = new TreeNode(0);
return helper(nums, 0, nums.length - 1);
}
TreeNode helper(int[] nums, int left, int right) {
//特殊情况
if (left > right) {
return null;
}
int mid = left + (right - left) / 2;
TreeNode node = new TreeNode(nums[mid]);
node.left = helper(nums, left, mid - 1);
node.right = helper(nums, mid + 1, right);
return node;
}
}