6-3 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

思路:

先根据二叉排序树的后序序列生成该二叉树,再求其高度。

如何根据一个二叉排序树的后序序列生成该二叉树?
  • 我们建立二叉树,就是确定根,然后建立该根的左子树、右子树。
  • 其中关键在于如何确定其左子树中节点的个数,对于前、中和后、中序列的,由于有中序序列,可以轻易确定左右子树中节点的个数。
  • 对于这个二叉排序树的后序序列,我们可以轻易找到根,然后序列中大于等于根的就是根的右子树中节点,小于根的就是左子树中的节点。
  • 后序序列:2 8 9 6 22 20 30 25 10

代码:

typedef struct BiNode
{
    int data;
    struct BiNode *Left,*Right;
}*BiTree;

BiTree CreateTree( int postorder[], int N );
BiTree CreateTree( int postorder[], int N )
{
    int i=0,root=0;
    BiTree T=(BiTree)malloc(sizeof(struct BiNode));
    if(N==0)
    {
        return NULL;
    }
    //确定根
    root=postorder[N-1];
    T->data=root;
    i=0;
    //确定左子树中节点个数,比根大的就是右子树中的节点,即可求得左子树中节点的个数(间接得到右子树中的节点个数)
    while(i<N)
    {
        if(postorder[i]>=root)
        {
            break;
        }
        i++;
    }
    T->Left=CreateTree(postorder,i);
    T->Right=CreateTree(postorder+i,N-i-1);
    return T;
}

int GetHight(BiTree BT);
int GetHight(BiTree BT)
{
    int hl=0,hr=0,maxh=0;
    if(BT)
    {
        hl=GetHight(BT->Left);
        hr=GetHight(BT->Right);
        if(hl>hr)
        {
            maxh=hl;
        }
        else
        {
            maxh=hr;
        }
        return maxh+1;
    }
    else
    {
        return 0;
    }
}


int Height_of_BST( int postorder[], int N );
int Height_of_BST( int postorder[], int N )
{
    BiTree BT;
    BT=(BiTree)malloc(sizeof(struct BiNode));
    BT=CreateTree(postorder,N);
    return GetHight(BT)-1;
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值