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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
#include <stdio.h>
#include <stdlib.h>

typedef char ElemType;

typedef struct TreeNode{
ElemType data;
struct TreeNode *lchild;
struct TreeNode *rchild;
}TreeNode;

TreeNode* createNode(ElemType e)
{
TreeNode *p = (TreeNode*)malloc(sizeof(TreeNode));
p->data = e;
p->lchild = NULL;
p->rchild = NULL;
return p;
}
//创建结点

TreeNode* initTree()
{
TreeNode *root = createNode('A');
root->lchild = createNode('B');
root->rchild = createNode('C');
root->lchild->lchild = createNode('D');
root->lchild->rchild = createNode('E');
root->rchild->lchild = createNode('F');
root->rchild->rchild = createNode('G');
return root;
}
//初始化一棵树

void preOrder(TreeNode *root)
{
if(root == NULL)
{
return;
}
printf("%c ",root->data);
preOrder(root->lchild);
preOrder(root->rchild);
}
//先序遍历

void inOrder(TreeNode *root)
{
if(root == NULL)
{
return;
}
inOrder(root->lchild);
printf("%c ",root->data);
inOrder(root->rchild);
}
//中序遍历

void postOrder(TreeNode *root)
{
if(root == NULL)
{
return;
}
postOrder(root->lchild);
postOrder(root->rchild);
printf("%c ",root->data);
}
//后序遍历

int countNode(TreeNode *root)
{
if(root == NULL)
{
return 0;
}
return countNode(root->lchild) + countNode(root->rchild) + 1;
}
//统计结点个数

int treeDepth(TreeNode *root)
{
if(root == NULL)
{
return 0;
}
int leftDepth = treeDepth(root->lchild);
int rightDepth = treeDepth(root->rchild);
return leftDepth > rightDepth ? leftDepth + 1 : rightDepth + 1;
}
//求树的深度

void freeTree(TreeNode *root)
{
if(root == NULL)
{
return;
}
freeTree(root->lchild);
freeTree(root->rchild);
free(root);
}
//释放树

int main()
{
TreeNode *root = initTree();
preOrder(root);
printf("\n");
inOrder(root);
printf("\n");
postOrder(root);
printf("\n");
printf("%d\n",countNode(root));
printf("%d\n",treeDepth(root));
freeTree(root);
return 0;
}