LeetCode_Convert Sorted Array to Binary Search Tree

Given an array where elements are sorted in ascending order, convert it to a height balanced BST.

  

 1 /**
 2  * Definition for binary tree
 3  * struct TreeNode {
 4  *     int val;
 5  *     TreeNode *left;
 6  *     TreeNode *right;
 7  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 8  * };
 9  */
10 class Solution {
11 public:
12     TreeNode * BST(vector<int> num, int left, int right)
13     {
14         //if(left > right ) return NULL;
15 
16         int mid = (right +left)/2;
17         
18         TreeNode *p = new TreeNode(num[mid]);
19     
20         p->left  =  left <=  mid-1 ? BST(num, left, mid-1) : NULL ;
21         p->right = mid+1 <= right  ? BST(num, mid+1, right): NULL ;
22       
23        return p;
24     }
25     TreeNode *sortedArrayToBST(vector<int> &num) {
26         // Start typing your C/C++ solution below
27         // DO NOT write int main() function
28         int size = num.size();
29         TreeNode *myTree = NULL;
30         
31         if(0 == size )
32              return myTree;
33         
34         myTree = BST(num, 0, size-1);
35         
36         return myTree;
37         
38         
39     }
40 };

 

  

posted @ 2013-07-11 20:45  冰点猎手  阅读(268)  评论(0编辑  收藏  举报