当前位置:网站首页>6-8 求二叉树高度(20分)
6-8 求二叉树高度(20分)
2022-08-07 01:41:00 【jie3606】
本题要求给定二叉树的高度。
函数接口定义:
int GetHeight( BinTree BT );
其中BinTree结构定义如下:
typedef struct TNode *Position;
typedef Position BinTree;
struct TNode{
ElementType Data;
BinTree Left;
BinTree Right;
};
要求函数返回给定二叉树BT的高度值。
裁判测试程序样例:
#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;
}
/* 你的代码将被嵌在这里 */
输出样例(对于图中给出的树):
4
解答
int GetHeight( BinTree BT ){
if(BT == NULL)
return 0;
int leftLen = GetHeight(BT->Left),rightLen = GetHeight(BT->Right);
return (leftLen>rightLen?leftLen:rightLen ) + 1;
}
完整的程序
#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;
}
BinTree CreatBinTree() {
ElementType dada;
scanf("%c",&dada);
if(dada =='1'){
return NULL;
}
BinTree root = (BinTree) malloc(sizeof (struct TNode));
root->Data = dada;
root->Left = CreatBinTree();
root->Right = CreatBinTree();
return root;
}
int GetHeight( BinTree BT ){
if(BT == NULL)
return 0;
int leftLen = GetHeight(BT->Left),rightLen = GetHeight(BT->Right);
return (leftLen>rightLen?leftLen:rightLen ) + 1;
}
边栏推荐
猜你喜欢
随机推荐
基于华为云ECS的目标检测与识别的昇腾AI开发体验【华为云至简致远】
gorm cannot update fields with foreign keys
改变UISegmentedControl样式,改变字体
CompletableFuture使用示例
程序员纷纷“跑路”一线城市,背后的原因是?丨黑马观察
time complexity and space complexity
[Verilog Basics] Some basic concepts of DFT (Design for Test) testability design
研究生来黑马学习,是一种怎样的体验?
【8.6】代码源 - 【前缀集】【矩阵游戏】【谁才是最终赢家?】
mysqlworkbench连接方式
Error when connecting to MySQL: 2059 - authentication plugin 'caching_sha2_password' cannot be loaded...
一文了解DataStore(Proto)
word中使用latex语言编写公式,
使用kibana本地连接服务器es
Software tools use 【 】 Latex quick-and-dirty 】 VSCode + MiKTeX + SmutraPDF (including forward search + reverse search)
php 生成pdf 图片转pdf
【LeetCode】1760.袋子里最少数目的球
xcode armv6 armv7 armv7s arm64
IO的基本概念
什么是P = NP?问题









