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 *sortedArrayToBST(vector<int> &num) {
13         return recursive(num, 0, num.size() - 1);
14     }
15     
16     TreeNode *recursive(vector<int> &num, int s, int e) {
17         if (s > e) return NULL;
18         int mid = (s + e) / 2;
19         TreeNode* root = new TreeNode(num[mid]);
20         root->left = recursive(num, s, mid - 1);
21         root->right = recursive(num, mid + 1, e);
22         return root;
23     }
24 };

 

posted @ 2014-06-12 16:38  linyx  阅读(165)  评论(0编辑  收藏  举报