题目描述
对于一个元素各不相同且按升序排列的有序序列,请编写一个算法,创建一棵高度最小的二叉查找树。
给定一个有序序列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;
}
};