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

Convert Sorted Array to Binary Search Tree

时间:2015-07-13 17:36:27      阅读:79      评论:0      收藏:0      [点我收藏+]

标签:

https://leetcode.com/problems/convert-sorted-array-to-binary-search-tree/

 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 * buildTree(vector<int>& nums,int n,int m)
13     {
14         if(n>m)
15             return NULL;
16         int middle=(m+n)/2;
17         TreeNode * left=buildTree(nums,n,middle-1);
18         TreeNode * right=buildTree(nums,middle+1,m);
19         TreeNode * temp=new TreeNode(nums[middle]);
20         temp->left=left;
21         temp->right=right;
22         return temp;
23         
24     }
25     TreeNode* sortedArrayToBST(vector<int>& nums) {
26         int size=nums.size();
27         TreeNode * res=buildTree(nums,0,size-1);
28         return res;
29     }
30 };

 

Convert Sorted Array to Binary Search Tree

标签:

原文地址:http://www.cnblogs.com/aguai1992/p/4643145.html

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