先序、中序、后续的区别就在于 遍历根的顺序,换句话说就是输出x的顺序
1.(1)先遍历根就是先序
(2)先遍历左,后遍历右,中间遍历根就是中序
(3)最后遍历根就是后序。
2.左右节点的顺序总是先左后右。
前中后序的遍历用到了dfs的思想,先遍历到底,再换下一个
【来个例题】U235557 [模板] 二叉树的先序遍历
输入:
6 4
5 3 1
2 6 0
4 0 5
3 0 0
1 2 0
6 0 0
输出:
4 5 3 1 2 6
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
const int N = 5005;
struct tr{
int l,r;
};
tr tree[N];
int a,b;
void dfs(int x){
if(x==0)return;
cout<<x<<" ";//本题中先考虑的是根,所以是先序遍历
dfs(tree[x].l);
dfs(tree[x].r);
}
int main(){
int n,p;//题目中已给出了最初的一个根节点
cin>>n>>p;
cin>>a;
cin>>tree[a].l>>tree[a].r;
for(int i=2;i<=n;i++){
cin>>b;
cin>>tree[b].l>>tree[b].r;
}
dfs(p);//所以是从最初的根节点开始搜的
return 0;
}