Converts a sorted array into a two-prong search tree with the smallest height
- Describe
- Notes
- Data
- Evaluation
Give a sorted array (from small to large) and convert it to a binary tree with the smallest height.
Precautions
There may exist multiple valid solutions and return any of them.
Have you ever encountered this problem in a real interview? YesWhich company is asking you this question?LinkedinAirbnbamazon cryptic Studios Span class= "BTN Btn-xs btn-white Company" >dropbox epic Systems tinyco hedvig facebook google uber yelp apple yahoo bloomberg zenefits twitter microsoft snapchat
Thank you for your feedback
Sample Example
Give the array [1,2,3,4,5,6,7]
, return
4 / 2 6 / \ / 1 3 5 7
这道题本来都打算放弃了,现在倒回头来重新看了一遍,做过树状数组和线段树的一些练习后是容易多了。
/** * Definition of TreeNode: * Class TreeNode {* Public: * int val; * TreeNode *left, *right; * TreeNode (int val) {* this->val = val; * this->left = This->right = NULL; * } *} */class Solution {public: / * * @param a:an integer array * @return: A tree Node * /TreeNode * SORTEDARRAYTOBST (vector<int> &A mp A) { //write your code here if (! A.size ()) return NULL; int R=a.size ()-1; int l=0; int m= (l+r) >>1; TreeNode *root=subnode (a,l,r); return root; } TreeNode *subnode (vector<int> a,int l,int R) { if (l>r) return NULL; int m= (l+r) >>1; TreeNode *root=new TreeNode (a[m]); Root->left=subnode (a,l,m-1); Root->right=subnode (a,m+1,r); return root; }};
Lintcode_177_ converting a sorted array to a two-fork search tree with a minimum height