第9-10周练习题2020——4-12 求二叉树高度 (10分)
发布日期:2021-05-06 20:35:15 浏览次数:31 分类:技术文章

本文共 954 字,大约阅读时间需要 3 分钟。

本题要求给定二叉树的高度。

函数接口定义:

int GetHeight( BinTree BT );其中BinTree结构定义如下:typedef struct TNode *Position;typedef Position BinTree;struct TNode{    ElementType Data;    BinTree Left;    BinTree Right;};

要求函数返回给定二叉树BT的高度值。

裁判测试程序样例:

#include 
#include
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;}/* 你的代码将被嵌在这里 */

输出样例(对于图中给出的树):

4

在这里插入图片描述
代码

int GetHeight( BinTree BT ){
int i=1,j=1,max=1;//左子树深度,右子树深度 if(!BT) return 0; else if(BT->Left||BT->Right)//左右子树至少有一个不为空 {
if(BT->Left) i=i+GetHeight(BT->Left); if(BT->Right) j=j+GetHeight(BT->Right); max=i>j?i:j; } else if(!BT->Left&&!BT->Right) return 1;//左右子树均为空 return max;}
上一篇:PAT (Basic Level) Practice (中文)——1002 写出这个数 (20分)
下一篇:第9-10周练习题2020——4-11 Isomorphic (10分)

发表评论

最新留言

逛到本站,mark一下
[***.202.152.39]2025年04月06日 09时43分19秒

关于作者

    喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!

推荐文章