LeetCode - Convert Sorted Array to Binary Search Tree

给出一个已排序的数组,将其转化为二叉查找树(BST)。

思路:取数组中间元素为根结点的value,则数组左侧、右侧分别为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 *convert(int *start, int *end)
13     {
14         if (start > end)
15             return NULL;
16         int *mid = start + (end - start)/2;
17         TreeNode *node = (TreeNode *)malloc(sizeof(TreeNode));
18         node->val = *mid;
19         node->left = convert(start, mid-1);
20         node->right = convert(mid+1, end);
21         return node;
22     }
23     TreeNode *sortedArrayToBST(vector<int> &num)
24     {
25         if (num.size() == 0)
26             return NULL;
27         return convert(&num[0], &num[num.size()-1]);
28     }
29 };

 

posted @ 2014-11-26 16:14  bournet  阅读(142)  评论(0编辑  收藏  举报