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: A sorted (increasing order) array
     * @return: A tree node
     */
    TreeNode *sortedArrayToBST(vector<int> &A) {
        // write your code here
        int len=A.size();
        if(len==0)
            return NULL;
        return build(A,0,len-1);
    }
    TreeNode *build(vector<int> &A,int s,int e)
    {
        if(s>e)
            return NULL;
        int m=(s+e)>>1;
        TreeNode *q=new TreeNode(A[m]);
            q->left=build(A,s,m-1);
            q->right=build(A,m+1,e);
        return q;
    }
};

  

posted @ 2017-08-30 15:34  会飞的雅蠛蝶  阅读(133)  评论(0编辑  收藏  举报