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

来源:互联网 发布:网络医院app 编辑:程序博客网 时间:2024/05/16 10:04

只有不断取中位数,才能确保高度最低。

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


0 0
原创粉丝点击