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
给一个升序数组,让重建一个AVL二叉搜索树
思路:
AVL就是左右子树高度差不能>1
N
h
N_{h}
Nh表示高度为h的node数
N h − 1 , N h − 2 N_{h-1}, N_{h-2} Nh−1,Nh−2表示左子树和右子树(不按顺序)
N
h
=
1
+
N
h
−
1
+
N
h
−
2
>
2
N
h
−
2
N_{h} = 1 + N_{h-1} + N_{h-2} > 2 N_{h-2}
Nh=1+Nh−1+Nh−2>2Nh−2
其中
N
h
N_{h}
Nh表示高度为h的node数
为了保持平衡,尽量左子树右子树node数一样
而已经知道BST中序遍历得到的是升序数组
中序遍历顺序:左子树,root,右子树
所以取中间元素作root
然后递归
//0ms
public TreeNode sortedArrayToBST(int[] nums) {
return buildTree(nums, 0, nums.length-1);
}
TreeNode buildTree(int[] nums, int start, int end) {
if(start > end) return null;
int rootIdx = start + (end - start) / 2;
TreeNode root = new TreeNode(nums[rootIdx]);
root.left = buildTree(nums, start, rootIdx-1);
root.right = buildTree(nums, rootIdx+1, end);
return root;
}