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

Leetcode | Convert Sorted Array to Binary Search Tree

时间:2014-06-16 00:33:31      阅读:252      评论:0      收藏:0      [点我收藏+]

标签:style   class   blog   code   java   http   

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

递归,二分法。

bubuko.com,布布扣
 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         return recursive(num, 0, num.size() - 1);
14     }
15     
16     TreeNode *recursive(vector<int> &num, int s, int e) {
17         if (s > e) return NULL;
18         int mid = (s + e) / 2;
19         TreeNode* root = new TreeNode(num[mid]);
20         root->left = recursive(num, s, mid - 1);
21         root->right = recursive(num, mid + 1, e);
22         return root;
23     }
24 };
bubuko.com,布布扣

 

Leetcode | Convert Sorted Array to Binary Search Tree,布布扣,bubuko.com

Leetcode | Convert Sorted Array to Binary Search Tree

标签:style   class   blog   code   java   http   

原文地址:http://www.cnblogs.com/linyx/p/3784207.html

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