'commit'
This commit is contained in:
59
TangDou/LuoGuBook/L16_5.cpp
Normal file
59
TangDou/LuoGuBook/L16_5.cpp
Normal file
@@ -0,0 +1,59 @@
|
||||
#include <bits/stdc++.h>
|
||||
|
||||
using namespace std;
|
||||
const int N = 1e6 + 10;
|
||||
//树的结构体+存储数组
|
||||
struct Node {
|
||||
int id; // 当前结点ID
|
||||
int left; // 左结点ID
|
||||
int right;// 右结点ID
|
||||
} t[N];
|
||||
int n;
|
||||
|
||||
/**
|
||||
测试用例:
|
||||
7
|
||||
2 7
|
||||
3 6
|
||||
4 5
|
||||
0 0
|
||||
0 0
|
||||
0 0
|
||||
0 0
|
||||
*/
|
||||
//前序遍历
|
||||
void pre_order(int x) {
|
||||
printf("%d ", x);
|
||||
if (t[x].left) pre_order(t[x].left);
|
||||
if (t[x].right) pre_order(t[x].right);
|
||||
}
|
||||
|
||||
//中序遍历
|
||||
void in_order(int x) {
|
||||
if (t[x].left) in_order(t[x].left);
|
||||
printf("%d ", x);
|
||||
if (t[x].right) in_order(t[x].right);
|
||||
}
|
||||
|
||||
//后序遍历
|
||||
void post_order(int x) {
|
||||
if (t[x].left) post_order(t[x].left);
|
||||
if (t[x].right) post_order(t[x].right);
|
||||
printf("%d ", x);
|
||||
}
|
||||
|
||||
int main() {
|
||||
cin >> n;
|
||||
//创建二叉树 build
|
||||
for (int i = 1; i <= n; i++) cin >> t[i].left >> t[i].right, t[i].id = i;
|
||||
//前序
|
||||
pre_order(1);
|
||||
printf("\n");
|
||||
//中序
|
||||
in_order(1);
|
||||
printf("\n");
|
||||
//后序
|
||||
post_order(1);
|
||||
printf("\n");
|
||||
return 0;
|
||||
}
|
||||
Reference in New Issue
Block a user