上图的示例。数组表示顺序为:8,3,1,6,4,7,10,14,13 我想找出高度而不构建树 ..... 基本上你有BST的数组表示,你需要在不构建树的情况下找出树的高度吗?
答案 0 :(得分:1)
这个问题可以使用递归方法解决,因为大多数树问题都已解决。
伪代码 -
int get_height(int a[], int low, int hi) {
if(low > hi)
return -1;
int root = a[low];
// Find position pos in the range (low+1) to hi such that
// all elements at left of pos are <= root and all elements at right
// of pos are > root. Do this using modified binary search
int pos = <position for root found as described above>
int ht = 1 + max (get_height(a, low+1, pos),
get_height(a, pos+1, hi));
return ht;
}