Title address:
Given an ascending array , to convert it into a BST, requires the height to reach the minimum.
Can be solved with recursion. take as the root of the tree, 是 middle number, then the left subtree and recursively established right subtree, can be connected to the root. code show as below:
public class Solution {
/*
* @param A: an integer array
* @return: A tree node
*/
public TreeNode sortedArrayToBST(int[] A) {
// write your code here
return buildTree(A, 0, A.length - 1);
}
private TreeNode buildTree(int[] A, int l, int r) {
if (l > r) {
return null;
}
int m = l + (r - l >> 1);
TreeNode root = new TreeNode(A[m]);
root.left = buildTree(A, l, m - 1);
root.right = buildTree(A, m + 1, r);
return root;
}
}
class TreeNode {
int val;
TreeNode left, right;
TreeNode(int x) {
val = x;
}
}
time complexity , space 。
First of all, we can use mathematical induction to prove that the established tree is indeed BST. Then we first prove that the tree is balanced (meaning that for each of its subtrees, the absolute value of the difference between the number of left and right subtree nodes does not exceed ). Mathematical induction: when or conclusion is established. Assuming conclusions for established at , when if is odd, then is just the index of the number in the center of the array. According to mathematical induction, the left and right subtrees are balanced, and the entire tree is also balanced, so the conclusion is true; is even, then takes the index of the left-most number in the center of the array, and the number of nodes in the left subtree is smaller than that in the right subtree , still right. So the conclusion is to any is right.
Then we prove that even for a general tree, when the tree is balanced, its height is the smallest. It can also be proved by mathematical induction. When the number of nodes in the tree is conclusion is true at o'clock; The tree conclusion of nodes is also established, when the tree has node, suppose its left and right subtrees have sum nodes, then obviously by mathematical induction, when the left and right subtrees are balanced, the height of the entire tree is the smallest. Let the root of the tree be , the left and right subtrees are and , set means is the height of the rooted tree. in case , then there is , so Assuming that the left subtree is moved one node to the right subtree, the left and right subtrees are respectively And , The number of nodes in the left subtree is still more than that in the right subtree by at least , so , that is, the height of the tree will become smaller. So when the tree is balanced, its height is the smallest.