树的遍历

二叉树的遍历

前序遍历

#include<bits/stdc++.h>
using namespace std;
int n;
struct s
{
	int l,r,d;
}a[10005];
void f(int t)//前序
{
	if(t==0)return;
	cout<<t<<' ';
	f(a[t].l);
	f(a[t].r);
}
int main()
{
    cin>>n;
    for(int i=1;i<=n;i++)cin>>a[i].d>>a[i].l>>a[i].r;
	f(a[1].d);
    return 0;
}

中序遍历

#include<bits/stdc++.h>
using namespace std;
int n;
struct s
{
	int l,r,d;
}a[10005];
void f(int t)//中序
{
	if(t==0)return;
	f(a[t].l);
	cout<<t<<' ';
	f(a[t].r);
}
int main()
{
    cin>>n;
    for(int i=1;i<=n;i++)cin>>a[i].d>>a[i].l>>a[i].r;
	f(a[1].d);
    return 0;
}

后序遍历

#include<bits/stdc++.h>
using namespace std;
int n;
struct s
{
	int l,r,d;
}a[10005];
void f(int t)//后序
{
	if(t==0)return;
	f(a[t].l);
	f(a[t].r);
    cout<<t<<' ';
}
int main()
{
    cin>>n;
    for(int i=1;i<=n;i++)cin>>a[i].d>>a[i].l>>a[i].r;
	f(a[1].d);
    return 0;
}
posted @ 2024-01-25 20:09  RTER  阅读(3)  评论(0编辑  收藏  举报