LeetCode --- Convert Sorted Array to Binary Search Tree

题目链接

Problem discription:

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

Accepted Code:

 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 *sortedArrayToBST(vector<int> &num, int start, int end) {
13         if (start > end) {
14             return NULL;
15         } 
16         // if you write " int middle = start + (end - start) >> 1"
17         // instead of the following sentence, you should keep in 
18         // mind that the priority of ">>" is weaker than "+" operator
19         int middle = start + (end - start) / 2;
20         TreeNode *p = new TreeNode(num[middle]);
21         // elements at the left of num[middle] construct
22         // the left child tree of "p" and its right child
23         // tree consists of elements located at the right
24         // of num[middle]...
25         // because the given array is sorted
26         if (start != end) {
27             p->left = sortedArrayToBST(num, start, middle - 1);
28             p->right = sortedArrayToBST(num, middle + 1, end);
29         }
30         return p;
31     }
32     TreeNode *sortedArrayToBST(vector<int> &num) {
33         // call the overload function
34         return sortedArrayToBST(num, 0, num.size() - 1);
35     }
36 };

 

posted on 2014-06-14 17:54  Stomach_ache  阅读(132)  评论(0编辑  收藏  举报

导航