二叉树的序遍历

背景

今天qer问我二叉树怎么进行前序遍历,中序遍历,后序遍历

前序遍历:根节点->左子树->右子树

中序遍历:左子树->根节点->右子树

后序遍历:左子树->右子树->根节点

如:

 

前序遍历:abdefgc

中序遍历:debgfac

后序遍历:edgfbca

代码实现(codevs3143):

#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
struct tree
{
	int l,r;
}t[105];
void qian(int a)//前序遍历
{
    if (a != 0)
	{
        cout << a << ' ';
        qian(t[a].l);
        qian(t[a].r);
    }
}
void zhong(int a)//中序遍历
{
    if (a != 0)
	{
        zhong(t[a].l);
        cout << a << ' ';
        zhong(t[a].r);
    }
}
void hou(int a)//后序遍历
{
    if (a != 0)
	{
        hou(t[a].l);
        hou(t[a].r);
        cout << a << ' ';
    }
}
int main()
{
	int n;
	cin>>n;
	for(int i = 1;i <= n;i ++)
	{
		cin>>t[i].l>>t[i].r;
	}
	qian(1);  cout<<endl;
	zhong(1);  cout<<endl;
	hou(1);  cout<<endl;
}
上一篇
下一篇