创建二叉查找树,返回最小高度

题目描述
对于一个元素各不相同且按升序排列的有序序列,请编写一个算法,创建一棵高度最小的二叉查找树。
给定一个有序序列int[] vals,请返回创建的二叉查找树的高度。

class MinimalBST {
public:
    TreeNode *buildBST(vector<int> vals,int left,int right) {
        if (left > right)
            return NULL;
        int middle = left + (right - left)/2;
        TreeNode *root = new TreeNode(vals[middle]);
        root->left = buildBST(vals,left,middle-1);
        root->right = buildBST(vals,middle+1,right);

        return root;

    }

    int highBST(TreeNode *root) {
        if (root == NULL)
            return 0;
        int left = highBST(root->left);
        int right = highBST(root->right);
        if (left > right)
            return left + 1;
        else
            return right + 1;
    }
    int buildMinimalBST(vector<int> vals) {
        // write code here
        int length = vals.size();
        if (length <= 0)
            return 0;
        TreeNode *root = buildBST(vals,0,length-1);
        return highBST(root);
    }
};
class MinimalBST {
public:
    int buildMinimalBST(vector<int> vals) {
        // write code here
        int n = vals.size();
        int height = 0;
        while(n){
            n /= 2;
            height++;
        }

        return height;
    }
};
    原文作者:二叉查找树
    原文地址: https://blog.csdn.net/coolwriter/article/details/79130655
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞