【2014】二叉树的遍历

27 篇文章 2 订阅
5 篇文章 0 订阅

问题描述:
输入一棵二叉树,输出树的前、中、后序遍历结果。

输入一个整数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;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值