easy!
Title Description:
Converts an ordered array in ascending order to a highly balanced binary search tree.
In the subject, a highly balanced binary tree refers to the absolute value of the height difference of the left and right two subtrees of each node of a binary tree not exceeding 1.
Example:
Given an ordered array: [ -10,-3,0,5,9], one possible answer is: [0,-3,9,-10,null,5], which can represent the following highly balanced binary search tree: 0 / -3 9 / /-10 5
Problem Solving Ideas:
This problem is to turn an ordered array into a binary search tree, the so-called binary search tree, is a always satisfy left < Root < Right (another more straightforward explanation, binary search tree: Empty tree or binary tree of all nodes than his left child node larger than his right child node small. ) of the characteristics of the two-fork tree, if the two-fork search tree in the middle order traversal, the result is an ordered array. So in turn, we can know 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 and the two sub-nodes, this is not the core idea of binary search method. So the problem is the two- point search method .
C + + Solution One:
1 /**2 * Definition for binary tree3 * struct TreeNode {4 * int val;5 * TreeNode *left;6 * TreeNode *right;7 * TreeNode (int x): Val (x), left (null), right (null) {}8 * };9 */Ten classSolution { One Public: ATreeNode *sortedarraytobst (vector<int> &num) { - returnSortedarraytobst (NUM,0, Num.size ()-1); - } theTreeNode *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; A } at};
Leetcode (108): Converting an ordered array to a two-fork search tree