码迷,mamicode.com
首页 > 其他好文 > 详细

[LeetCode] Convert Sorted Array to Binary Search Tree

时间:2015-01-20 22:00:43      阅读:170      评论:0      收藏:0      [点我收藏+]

标签:

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

思路:递归的思路。思路与重建二叉树类似。时间复杂度O(n), 空间复杂度O(logN)

 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         if (num.empty()) return NULL;
14         return sortedArrayToBST(num, 0, num.size() - 1);
15     }
16     TreeNode* sortedArrayToBST(vector<int> &num, int start, int last) {
17         if (start > last) return NULL;
18         
19         int half = (start + last) >> 1;
20         TreeNode* root = new TreeNode(num[half]);
21         root->left = sortedArrayToBST(num,start, half - 1);
22         root->right = sortedArrayToBST(num, half + 1, last);
23         
24         return root;
25     }
26 };

 

[LeetCode] Convert Sorted Array to Binary Search Tree

标签:

原文地址:http://www.cnblogs.com/vincently/p/4237216.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!