forked from cat-note/bottleofcat
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDS-6-8.c
84 lines (73 loc) · 1.96 KB
/
DS-6-8.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
/*
本题要求给定二叉树的高度,需实现的方法如下:
int GetHeight( BinTree BT );
要求函数返回给定二叉树BT的高度值。
输入样例(先序遍历序列):
ABD##FE###CG#H##I##
输出样例:
4
代码长度限制
16 KB
时间限制
400 ms
内存限制
64 MB
*/
#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 CreateBinTree();
BinTree TreeGrow(BinTree tree);
int GetHeight(BinTree BT);
int main()
{
BinTree BT = CreateBinTree();
printf("%d\n", GetHeight(BT));
return 0;
}
// 以下为题解代码
int GetHeight(BinTree BT)
{
if (BT == NULL) // 空树
return 0;
int leftHeight = GetHeight(BT->Left); // 获得左树高度
int rightHeight = GetHeight(BT->Right); // 获得右树高度
// 找更高的一棵子树, 将其高度+1返回, 也算一种贪心吧
return (leftHeight > rightHeight ? leftHeight : rightHeight) + 1;
}
// 我顺带写了这个树生成函数, 用于测试
BinTree CreateBinTree()
{
return TreeGrow(NULL);
}
// 先序遍历序列生成树
BinTree TreeGrow(BinTree tree)
{
char chr = getchar();
if (chr == '#')
{
return NULL;
}
else
{
tree = (BinTree)malloc(sizeof(struct TNode));
tree->Data = chr;
tree->Left = TreeGrow(tree->Left);
tree->Right = TreeGrow(tree->Right);
return tree;
}
}
/*
吐槽:题目中创建树的函数他原本写成CreatBinTree了,经典Create掉了e
本题很适合用递归来解决问题,每次递归都选取左右子树中高度更高的一棵子树,然后将其高度+1返回即可。
递归深入到某个空节点的时候终止,返回0,然后回溯到上一层。
- SomeBottle 2022.12.5
*/