You are supposed to write a function of finding the height of a binary search tree with the given postorder sequence.
Format of function:
int Height_of_BST( int postorder[], int N );
where the postorder sequence is stored in
int postorder[]
, and the integerN
is the number of nodes in the tree, which is guaranteed to be positive. The functionHeight_of_BST
is supposed to return the height of the binary search tree.Note:
- It is guaranteed that the postorder sequence consists of distinct integers and does correspond to a binary search tree.
- You may assume that
MAXN
is a small number (less than 100) in the judge's program.Sample program of judge:
#include <stdio.h> #include <stdlib.h> #define MAXN 10 int Height_of_BST( int postorder[], int N ); int main() { int postorder[MAXN], N, i; scanf("%d", &N); for (i=0; i<N; i++) scanf("%d", &postorder[i]); printf("%d\n", Height_of_BST(postorder, N)); return 0; } /* Your function will be put here */
Sample Input:
9 2 8 9 6 22 20 30 25 10
Sample Output:
3
int Height_of_BST( int postorder[] , int N){
if(N){
int index;
for(index = N - 1;index >= 0;index --){
if(postorder[index] < postorder[N - 1]){
break;
}
}
int left = Height_of_BST(postorder, index + 1); //递归左子树
int right = Height_of_BST(postorder + index + 1, N-index-1-1);//递归右子树
int height = (left > right ? left : right);
return height + 1;
}
return -1; //递归出口
}