Height of Binary Search Tree (25 分)

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 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 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; //递归出口
    
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

R_1220

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值