问题描述:
输入一棵二叉树,输出树的前、中、后序遍历结果。输入一个整数N(N<= 10000),表示树中有N个结点(编号0~N-1)。
接下来N行,依次为结点0~结点N-1的左右孩子情况。
每行3个整数,F,L,R。L,R为F的左右孩子。L,R如果为-1表示该位置上没有孩子。
分三行分别输出树的前中后序遍历。
同一行中的数字,用一个空格间隔。
输入:5
0 3 1
1 2 -1
2 -1 4
3 -1 -1
4 -1 -1
输出:0 3 1 2 4
3 0 2 4 1
3 4 2 1 0
题目没有告诉根结点,所以需要设置一个bool数组来寻找:L,R对应结点一定不是根结点
#include<iostream>
using namespace std;
const int maxn = 11000;
struct node {
int left, right;
}Node[maxn];
bool isRoot[maxn] = { true };
void preorder(int root) {
if (root == -1)
return;
cout << root << " ";
preorder(Node[root].left);
preorder(Node[root].right);
}
void inorder(int root) {
if (root == -1)
return;
inorder(Node[root].left);
cout << root << " ";
inorder(Node[root].right);
}
void postorder(int root) {
if (root == -1)
return;
postorder(Node[root].left);
postorder(Node[root].right);
cout << root << " ";
}
int main() {
int n,x,l,r;
cin >> n;
for (int i = 0; i < n; i++) {
cin >> x >> l >> r;
Node[x].left = l;
Node[x].right = r;
if (l != -1)
isRoot[l] = false;
if (r != -1)
isRoot[r] = false;
}
int root = -1;
for (int i = 0; i < n; i++) {
if (isRoot[i] != false)
root = i;
}
preorder(root);
cout << endl;
inorder(root);
cout << endl;
postorder(root);
system("pause");
return 0;
}