Given an array where elements is sorted in ascending order, convert it to a height balanced BST.
The explanation of the complete copy from ref, thanks!
“
The following:
First review what is a two-fork search tree (quoted from Wikipedia):
The two-fork search tree (binary searchtrees), also called ordered Binary tree (ordered binary tree), sorts the binary trees (sorted binary), Refers to an empty tree or a two-fork tree with the following properties:
- If the left subtree of any node is not empty, the value of all nodes on the left subtree is less than the value of its root node;
- The right subtree of any node is not empty, then the value of all nodes on the right subtree is greater than the value of its root node;
- The left and right subtrees of any node are also two-fork lookup trees, respectively.
Then review what is the balanced binary tree (quoted Geekforgeek):
An empty tree is height-balanced. A non-empty binary Tree T is balanced if:
1) left subtree of T-is balanced
2) Right subtree of T-is balanced
3) The difference between heights of left subtree and right subtree are not more than 1.
The workaround is to select the point to construct the root node, and then recursively construct the Saozi right subtree.
”
Tree Construction Basic Problem http://www.cnblogs.com/springfor/p/3879823.html
Public classSolution { PublicTreeNode Sortedarraytobst (int[] nums) { if(nums==NULL|| nums.length==0)return NULL; returnHelper (nums, 0, Nums.length-1); } PublicTreeNode Helper (int[] num,intLowintHigh ) { if(Low>high)return NULL; intMid = (Low+high)/2; TreeNode Root=NewTreeNode (Num[mid]); Root.left= Helper (Num,low, mid-1); Root.right= Helper (num, mid+1, high); returnRoot; }}
Convert Sorted Array to Binary Search Tree