You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
59 lines
1.0 KiB
59 lines
1.0 KiB
#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;
|
|
} |