C++树的遍历(前序遍历 中序遍历 后续遍历)

遍历树存在如下的方式:

  • 前序遍历(Preorder Tree Walk)按照根节点—左子树—右子树顺序遍历
  • 中序遍历(Inoder Tree Walk)按照左子树—根节点—右子树顺序遍历
  • 后序遍历(Postorder Tree Walk)按照左子树—右子树—根节点顺序遍历

使用递归的方式遍历

#include <iostream>
using namespace std;

const int MAX = 100000;
const int NIL = -1;

struct Node {
	int p, l, r;
};

Node T[MAX];
int n;

void PreParse(int u)//前序遍历
{
	if (u == NIL) return;
	cout << u << " ";
	PreParse(T[u].l);
	PreParse(T[u].r);
}

void InParse(int u) //中序遍历
{
	if (u == NIL) return;
	InParse(T[u].l);
	cout << u << " ";
	InParse(T[u].r);
}

void PostParse(int u) //后序遍历
{
	if (u == NIL) return;
	PostParse(T[u].l);
	PostParse(T[u].r);
	cout << u << " ";
}

int main()
{
	int v, l, r, root = 0;
	cin >> n;
	for (int i = 0; i < n; i++) {
		cin >> v >> l >> r;
		T[v].l = l;
		T[v].r = r;
		if (l != NIL) T[l].p = v;
		if (r != NIL) T[r].p = v;
	}
	for (int i = 0; i < n; i++)
		if (T[i].p == NIL)
			root = i;
	cout << "Preorder:";
	PreParse(root);
	cout << endl << "Inordr:";
	InParse(root);
	cout << endl << "Postorder:";
	PostParse(root);
	return 0;
}
/*
input:
9
0 1 4
1 2 3
2 -1 -1
3 -1 -1
4 5 8
5 6 7
6 -1 -1
7 -1 -1
8 -1 -1
*/
/*
output:
Preorder:0 1 2 3 4 5 6 7 8
Inordr:2 1 3 0 6 5 7 4 8
Postorder:2 3 1 6 7 5 8 4 0
*/
  • 6
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值