6-3 Height of BST (25 分)

题目

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
结尾无空行

思路

题意:根据给出的先序遍历序列得到这个二叉搜索树的高度

什么是二叉搜索树?

  1. 左子树上的所有结点小于等于根结点的值
  2. 右子树上的所有结点大于等于根结点的值
  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;
}
  • 2
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值