数据结构——求二叉树高度

这个题。。。有点迷。。。

首先注意题干,人家让你写的是Getheight函数,那个构建树那个函数 是被忽略掉不需要去写的,一开始还在为怎么去构建这个树想了半天。。。。

裁判测试程序样例:

#include <stdio.h>
#include <stdlib.h>

typedef char ElementType;
typedef struct TNode *Position;
typedef Position BinTree;
struct TNode{
    ElementType Data;
    BinTree Left;
    BinTree Right;
};

BinTree CreatBinTree(); /* 实现细节忽略 */
int GetHeight( BinTree BT );

int main()
{
    BinTree BT = CreatBinTree();
    printf("%d\n", GetHeight(BT));
    return 0;
}
/* 你的代码将被嵌在这里 */

 

题目解法:简单的递归,遍历每一个分支,遍历次数最多的那个分支加一就是最大的层数

直接给出AC代码:

int GetHeight(BinTree BT)
{
    int len1,len2;
    if(BT==NULL) return 0;
    len1=GetHeight(BT->Left);
    len2=GetHeight(BT->Right);
    if(len1>len2) return len1+1;
    else return len2+1;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值