codevs 3143 二叉树的序遍历
Description
求一棵二叉树的前序遍历,中序遍历和后序遍历
Input
第一行一个整数n,表示这棵树的节点个数。
接下来n行每行2个整数L和R。第i行的两个整数Li和Ri代表编号为i的节点的左儿子编号和右儿子编号。
Output
输出一共三行,分别为前序遍历,中序遍历和后序遍历。编号之间用空格隔开。
Sample Input
5
2 3
4 5
0 0
0 0
0 0
Sample Output
1 2 4 5 3
4 2 5 1 3
4 5 2 3 1
思路
#include<bits/stdc++.h>
using namespace std;
const int maxn = 20;
int lson[maxn] = {0},rson[maxn] = {0};
void preorder(int x)
{
	if (x != 1)	printf(" ");
	printf("%d",x);
	if (lson[x])	preorder(lson[x]);
	if (rson[x])	preorder(rson[x]);
}
void inorder(int x)
{
	if (x)
	{
		inorder(lson[x]);
		printf("%d ",x);
		inorder(rson[x]); 
	}
}
void postorder(int x)
{
	if (lson[x])	postorder(lson[x]);
	if (rson[x])	postorder(rson[x]);
	printf("%d ",x); 
}
int main()
{
	int N;
	scanf("%d",&N);
	for (int i = 1;i <= N;i++)	scanf("%d%d",&lson[i],&rson[i]);
	preorder(1);printf("\n");
	inorder(1);printf("\n");
	postorder(1);printf("\n");
	return 0;
}
┆ 凉 ┆ 暖 ┆ 降 ┆ 等 ┆ 幸 ┆ 我 ┆ 我 ┆ 里 ┆ 将 ┆ ┆ 可 ┆ 有 ┆ 谦 ┆ 戮 ┆ 那 ┆ ┆ 大 ┆ ┆ 始 ┆ 然 ┆
┆ 薄 ┆ 一 ┆ 临 ┆ 你 ┆ 的 ┆ 还 ┆ 没 ┆ ┆ 来 ┆ ┆ 是 ┆ 来 ┆ 逊 ┆ 没 ┆ 些 ┆ ┆ 雁 ┆ ┆ 终 ┆ 而 ┆
┆ ┆ 暖 ┆ ┆ 如 ┆ 地 ┆ 站 ┆ 有 ┆ ┆ 也 ┆ ┆ 我 ┆ ┆ 的 ┆ 有 ┆ 精 ┆ ┆ 也 ┆ ┆ 没 ┆ 你 ┆
┆ ┆ 这 ┆ ┆ 试 ┆ 方 ┆ 在 ┆ 逃 ┆ ┆ 会 ┆ ┆ 在 ┆ ┆ 清 ┆ 来 ┆ 准 ┆ ┆ 没 ┆ ┆ 有 ┆ 没 ┆
┆ ┆ 生 ┆ ┆ 探 ┆ ┆ 最 ┆ 避 ┆ ┆ 在 ┆ ┆ 这 ┆ ┆ 晨 ┆ ┆ 的 ┆ ┆ 有 ┆ ┆ 来 ┆ 有 ┆
┆ ┆ 之 ┆ ┆ 般 ┆ ┆ 不 ┆ ┆ ┆ 这 ┆ ┆ 里 ┆ ┆ 没 ┆ ┆ 杀 ┆ ┆ 来 ┆ ┆ ┆ 来 ┆

 
                
            
         
         浙公网安备 33010602011771号
浙公网安备 33010602011771号