LeetCode108:Convert Sorted Array to Binary Search Tree
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 ofevery 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
意思是把一个有序数组拿来建成一棵平衡的二叉检索树。
要使二叉树平衡的话,每个结点的左子树与右子树最大的高度差为1;
其实我们只要保证每个结点的左子树中的结点和右子树的结点数量基本一致就行了。由于数组是有序的,我们很容易能找到数组的中间位置,而中间位置的数全部比其左边小,故左边的数应全在其左子树中,同理,右边的数应全在其右子树中。左半边的树为了区分其相对顺序,重复上述操作,右边的也是。递归的基础条件是刚好划分到只有一个数的时候,就不用考虑其左右子树了。