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

【leetcode】Convert Sorted Array to Binary Search Tree

时间:2015-01-11 12:10:19      阅读:137      评论:0      收藏:0      [点我收藏+]

标签:

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        
14         TreeNode *root=buildTree(num,0,num.size()-1);
15         return root;
16     }
17    
18    
19     TreeNode *buildTree(vector<int> &num,int l,int r)
20     {
21         if(l>r) return NULL;
22        
23         int mid=(l+r)/2;
24        
25         TreeNode *root=new TreeNode(num[mid]);
26         root->left=buildTree(num,l,mid-1);
27         root->right=buildTree(num,mid+1,r);
28        
29         return root;
30     }
31 };

 

【leetcode】Convert Sorted Array to Binary Search Tree

标签:

原文地址:http://www.cnblogs.com/reachteam/p/4216234.html

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