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

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

 

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

注意事项

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;
    }
};

  

posted @ 2017-10-29 21:41  会飞的雅蠛蝶  阅读(487)  评论(0编辑  收藏  举报