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

Convert Sorted Array to Binary Search Tree

时间:2015-01-23 19:56:34      阅读:202      评论:0      收藏:0      [点我收藏+]

标签:

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

 思路比较简单,就是每次以中位数为根节点,然后左边即左子树,右边是右子树,递归下去即可

超时代码(不知道为啥):

class Solution{
public:
     void dfs(TreeNode*  &root,vector<int> num,int start,int end){
        int mid=(start+end)/2;
        root=new TreeNode(num[mid]);
        if(start<=mid-1)
            dfs(root->left,num,start,mid-1);
        if(mid+1<=end)
            dfs(root->right,num,mid+1,end);
        return;
    }
    TreeNode *sortedArrayToBST(vector<int> &num) {
        if(num.empty()) return NULL;
        TreeNode* root=NULL;
        dfs(root,num,0,num.size()-1);
        return root;
    }
};

 

AC代码:

class Solution{
public:
     TreeNode *createTree(vector<int> &num, int start, int end)
    {
    //    if (start > end) return NULL;
        int mid = (start+end)/2;
        TreeNode *node = new TreeNode(num[mid]);
        if(start<=mid-1)
            node->left = createTree(num, start, mid-1);
        if(mid+1<=end)
            node->right = createTree(num, mid+1, end);
        return node;
    }
    TreeNode *sortedArrayToBST(vector<int> &num) {
        if(num.empty()) return NULL;
        return createTree(num,0,num.size()-1);
    }
};

 

Convert Sorted Array to Binary Search Tree

标签:

原文地址:http://www.cnblogs.com/fightformylife/p/4244783.html

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