-
Notifications
You must be signed in to change notification settings - Fork 0
/
BinaryTree.cpp
145 lines (135 loc) · 2.43 KB
/
BinaryTree.cpp
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
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#include <string>
#include <iostream>
#include <stack>
#include <queue>
using namespace std;
//二叉树节点定义
typedef struct BiTNode{
char data;
BiTNode *lchild;
BiTNode *rchild;
}BiTNode;
//创建二叉树
void CreateBiTree(BiTNode* &Tree)
{
char ch;
cin>>ch;
if(ch == '#')
Tree = NULL;
else
{
Tree = new BiTNode;
Tree->data = ch;
CreateBiTree(Tree->lchild);
CreateBiTree(Tree->rchild);
}
}
//前序遍历
void PreOrder(BiTNode *Tree)
{
if(Tree==NULL)
return;
cout<<Tree->data;
PreOrder(Tree->lchild);
PreOrder(Tree->rchild);
}
//中序遍历
void InOrder(BiTNode *Tree)
{
if(Tree==NULL)
return;
InOrder(Tree->lchild);
cout<<Tree->data;
InOrder(Tree->rchild);
}
//后序遍历
void LastOrder(BiTNode *Tree)
{
if(Tree==NULL)
return;
LastOrder(Tree->lchild);
LastOrder(Tree->rchild);
cout<<Tree->data;
}
//二叉树高度/深度
int BiTreeHeight(BiTNode *Tree)
{
if(Tree == NULL)
return 0;
int left = BiTreeHeight(Tree->lchild);
int right = BiTreeHeight(Tree->rchild);
return (left>right)?(left+1):(right+1);
}
// 二叉树层序遍历,利用队列(FIFO原则),先将根节点push,然后依次push根节点的左右节点,然后队列pop
void BFS(BiTNode *Tree)
{
if(Tree==NULL)
return ;
queue<BiTNode*> queueTree;
queueTree.push(Tree);
BiTNode *pNode;
while(!queueTree.empty())
{
pNode = queueTree.front();
cout<<pNode->data;
if(pNode->lchild!=NULL)
queueTree.push(pNode->lchild);
if(pNode->rchild!=NULL)
queueTree.push(pNode->rchild);
queueTree.pop();
}
cout<<endl;
}
// 分行从上到下打印二叉树
void PrintTreeByLine(BiTNode *Tree)
{
if(Tree==NULL)
return;
queue<BiTNode*> Q;
Q.push(Tree);
int nextLevel = 0;
int toBePrinted = 1;
while(!Q.empty())
{
BiTNode *pNode = Q.front();
cout<<pNode->data;
if(pNode->lchild)
{
Q.push(pNode->lchild);
nextLevel++;
}
if(pNode->rchild)
{
Q.push(pNode->rchild);
nextLevel++;
}
Q.pop();
--toBePrinted;
if(toBePrinted == 0)
{
printf("\n");
toBePrinted = nextLevel;
nextLevel = 0;
}
}
// cout<<endl;
}
int main(int argc, char const *argv[])
{
/* code */
BiTNode *Tree;
CreateBiTree(Tree);
// PreOrder(Tree);
// cout<<endl;
// InOrder(Tree);
// cout<<endl;
// LastOrder(Tree);
// cout<<endl;
// cout<<BiTreeHeight(Tree)<<endl;
PrintTreeByLine(Tree);
return 0;
}