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

Convert Sorted Array to Binary Search Tree

时间:2016-02-25 11:42:24      阅读:116      评论:0      收藏:0      [点我收藏+]

标签:

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

 

Subscribe to see which companies asked this question

Show Tags
Show Similar Problems
 
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
 
class Solution {
public:
    TreeNode *build(vector<int> &num, int l, int r) {
        if (l <= r)
        {
            int m = (l+r)/2;
            TreeNode *root = new TreeNode(num[m]);
            root->left = build(num,l,m-1);
            root->right = build(num,m+1,r);
            return root;
        }
        else
        {
            return NULL;
        }
        
    }
    TreeNode *sortedArrayToBST(vector<int> &num) {
        int n = num.size();
        if (n == 0)
            return 0;
        return build(num,0,n-1);
    }
};

 

Convert Sorted Array to Binary Search Tree

标签:

原文地址:http://www.cnblogs.com/SpeakSoftlyLove/p/5216158.html

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