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

[LeetCode]Convert Sorted Array to Binary Search Tree

时间:2015-12-17 20:42:02      阅读:122      评论:0      收藏:0      [点我收藏+]

标签:

题目描述:(链接)

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

解题思路:

 1 /**
 2  * Definition for a binary tree node.
 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>& nums) {
13         sortedArrayToBST(begin(nums), end(nums));
14     }
15 private:
16     TreeNode* sortedArrayToBST(vector<int>::iterator begin, vector<int>::iterator end) {
17         auto len = distance(begin, end);
18         if (len <= 0) return nullptr; 
19         auto mid = begin + len / 2;
20         TreeNode *root = new TreeNode(*mid);
21         root->left = sortedArrayToBST(begin, mid);
22         root->right = sortedArrayToBST(mid + 1, end);
23     }
24 };

 

[LeetCode]Convert Sorted Array to Binary Search Tree

标签:

原文地址:http://www.cnblogs.com/skycore/p/5055101.html

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