Given an array where elements is sorted in ascending order, convert it to a height balanced BST.
This problem is to turn an ordered array into a binary search tree, the so-called binary search tree, is always satisfied with the left < Root < right features, if the two-fork search tree by the middle sequence traversal, the result is an ordered array. So in turn, we can be informed that the root node should be an ordered array of intermediate points, from the middle point to the left and right two ordered arrays, in each of the points as the original middle point of the left or right two sub-nodes, this is not the core idea of binary search method. So this question is the two-point search method, the code is as follows:
/** Definition for binary tree * struct TreeNode {* int val; * TreeNode *left; * TreeNode *right; * T Reenode (int x): Val (x), left (null), right (NULL) {} *}; */classSolution { Public: TreeNode*sortedarraytobst (vector<int> &num) { returnSortedarraytobst (NUM,0, Num.size ()-1); } TreeNode*sortedarraytobst (vector<int> &num,intLeftintRight ) { if(Left > right)returnNULL; intMid = (left + right)/2; TreeNode*cur =NewTreeNode (Num[mid]); Cur->left = Sortedarraytobst (num, left, mid-1); Cur->right = Sortedarraytobst (num, mid +1, right); returncur; }};
[Leetcode] Convert Sorted array to binary search tree convert ordered array to binary