二叉树的3种遍历其实差不多,只是输出时机不一样,都是通过树根找儿子来深搜递归的。
下面是三种遍历的代码:
void first(int p){
if(p==0)
return;
printf("%d ",p);
first(tree[p].l);
first(tree[p].r);
}
void mid(int p){
if(p==0)
return;
mid(tree[p].l);
printf("%d ",p);
mid(tree[p].r);
}
void back(int p){
if(p==0)
return;
back(tree[p].l);
back(tree[p].r);
printf("%d ",p);
}
RT,对于这样一个二叉树,三个程序输出是这样的:
3 1 2 4 8 5 6 7
2 1 8 4 3 6 7 5
2 8 4 1 7 6 5 3
非递归版:
#include<cstdio>
#include<stack>
using namespace std;
struct tree{
int l,r;
}tree[100005];
void first(int p){
if(p==0) return ;
stack<int>sta;
sta.push(p);
while(!sta.empty()){
p=sta.top();sta.pop();
printf("%d ",p);
if(tree[p].r) sta.push(tree[p].r);
if(tree[p].l) sta.push(tree[p].l);
}
}
void mid(int p){
if(p==0) return;
stack<int>sta;
while(p || !sta.empty()){
if(p){
sta.push(p);
p=tree[p].l;
}
else{
printf("%d ",sta.top());
p=tree[sta.top()].r;
sta.pop();
}
}
}
void back(int p){
if(p==0) return;
stack<int>sta;
int pre=0;
while(p || !sta.empty()){
if(p){
sta.push(p);
p=tree[p].l;
}
else{
if(tree[sta.top()].r && tree[sta.top()].r!=pre)
p=tree[sta.top()].r;
else
{
printf("%d ",sta.top());
pre=sta.top();
sta.pop();
}
}
}
}
int main(){
int n,a,b,c,fa[100005]={};
scanf("%d",&n);
while(~scanf("%d%d%d",&a,&b,&c))
{
tree[a].l=b,tree[a].r=c;
fa[b]=fa[c]=a;
}
int root=0;
for(int i=1;i<=n;i++)
if(!fa[i])
root=i;
printf("%d\n",root);
first(root);puts("");
mid(root);puts("");
back(root);puts("");
}