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

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

样例
样例 1:

输入:[]
输出:{}
解释:二叉搜索树为空
样例 2:

输入:[1,2,3,4,5,6,7]
输出: {4,2,6,1,3,5,7}
解释:
拥有最小高度的二叉搜索树

         4
       /   \
      2     6
     / \    / \
    1   3  5   7
注意事项
There may exist multiple valid solutions, return any of them.
/**
 * 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.empty()) return NULL;
        TreeNode*newroot=builtree(A,0,A.size()-1);
        return newroot;
    }
    TreeNode*builtree(vector<int>&A,int low,int high)
    {
        if(low>high) return NULL;
        int mid=low+(high-low)/2;
        TreeNode* newroot=new TreeNode(A[mid]);
        newroot->left=builtree(A,low,mid-1);
        newroot->left=builtree(A,mid+1,high);
        return newroot;
    }
};
发布了330 篇原创文章 · 获赞 13 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/weixin_43981315/article/details/103923834