题目
You are supposed to write a function of finding the height of a binary search tree with the given preorder sequence.
Format of function:
int Height_of_BST( int preorder[], int N );
where the preorder sequence is stored in int preorder[]
, and the integer N
is the number of nodes in the tree, which is guaranteed to be positive. The function Height_of_BST
is supposed to return the height of the binary search tree.
Note:
- It is guaranteed that the preorder 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 preorder[], int N );
int main()
{
int preorder[MAXN], N, i;
scanf("%d", &N);
for (i=0; i<N; i++) scanf("%d", &preorder[i]);
printf("%d\n", Height_of_BST(preorder, N));
return 0;
}
/* Your function will be put here */
Sample Input:
9
10 6 2 9 8 25 20 22 30
结尾无空行
Sample Output:
3
结尾无空行
思路
题意:根据给出的先序遍历序列得到这个二叉搜索树的高度
什么是二叉搜索树?
- 左子树上的所有结点小于等于根结点的值
- 右子树上的所有结点大于等于根结点的值
- 任意结点的左子树和右子树结点满足上述两条件,即也为二叉搜索树
由先序遍历的特点可以得知,第一个结点即为根节点;
对先序遍历的序列遍历一次,找到左子树和右子树的分界点,即大于等于根节点的值时,就可break,则此时index的值是右子树的开始位置。左子树结点个数为Index-1个,右子树结点个数为N-index个;递归时,左子树从第一个结点开始(每次都要加1),右子树从index位置开始;
代码
int Height_of_BST( int preorder[], int N )
{
if(N)
{
int index;
for(index=0; index<N; index++)
{
if(preorder[index] > preorder[0]) break;
}
int m = Height_of_BST(preorder+1, index-1);
int n = Height_of_BST(preorder+index, N-index);
if(m < n) return n+1;
else return m+1;
}
return -1;
}