码迷,mamicode.com
首页 > 编程语言 > 详细

lintcode_177_把排序数组转换为高度最小的二叉搜索树

时间:2017-10-29 23:07:17      阅读:293      评论:0      收藏:0      [点我收藏+]

标签:def   bin   minimal   body   tin   modal   tabs   test   strong   

把排序数组转换为高度最小的二叉搜索树

 

给一个排序数组(从小到大),将其转换为一棵高度最小的排序二叉树。

注意事项

There may exist multiple valid solutions, return any of them.

样例

给出数组 [1,2,3,4,5,6,7], 返回

     4
   /     2     6
 / \    / 1   3  5   7


这道题本来都打算放弃了,现在倒回头来重新看了一遍,做过树状数组和线段树的一些练习后是容易多了。
/**
 * Definition of TreeNode:
 * class TreeNode {
 * public:
 *     int val;
 *     TreeNode *left, *right;
 *     TreeNode(int val) {
 *         this->val = val;
 *         this->left = this->right = NULL;
 *     }
 * }
 */


class Solution {
public:
    /*
     * @param A: an integer array
     * @return: A tree node
     */
    TreeNode * sortedArrayToBST(vector<int> &A) {
        // write your code here
        if(!A.size())
            return NULL;
        int r=A.size()-1;
        int l=0;
        int m=(l+r)>>1;
        TreeNode *root=subNode(A,l,r);
        return root;
    }
    TreeNode *subNode(vector<int> A,int l,int r)
    {
        if(l>r)
            return NULL;
        int m=(l+r)>>1;
        TreeNode *root=new TreeNode(A[m]);
        root->left=subNode(A,l,m-1);
        root->right=subNode(A,m+1,r);
        return root;
    }
};

  

lintcode_177_把排序数组转换为高度最小的二叉搜索树

标签:def   bin   minimal   body   tin   modal   tabs   test   strong   

原文地址:http://www.cnblogs.com/ygtzds/p/7751448.html

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