二叉树的三种遍历方式

来源:互联网 发布:淘宝电子发票在哪里app 编辑:程序博客网 时间:2024/06/05 12:39

二叉树的三种递归建树的方式

///测试数据:abc##de#g##f###

#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
struct Tree{
    char c;
    Tree *l,*r;
}T;
void Creat(Tree *&x){
    char n;
    cin>>n;
    if(n=='#'){
        x=NULL;
        return;
    }
    else{
        x=new Tree;
        x->c=n;
        Creat(x->l);
        Creat(x->r);
    }
}
void zhong(Tree *x){
    if(x==NULL)
        return;
    zhong(x->l);
    cout<<x->c;
    zhong(x->r);
}
void qian(Tree *x){
    if(x==NULL)
        return;
    cout<<x->c;
    qian(x->l);
    qian(x->r);
}
void hou(Tree *x){
    if(x==NULL)
        return;
    hou(x->l);
    hou(x->r);
    cout<<x->c;
}
int main(){
    char s[100];
    Tree *x;
    Creat(x);
    //cout<<"前序:"<<endl;
    qian(x);
    cout<<endl;
    //cout<<"中序:"<<endl;
    zhong(x);
    cout<<endl;
   // cout<<"后序:"<<endl;
    hou(x);
    cout<<endl;
    return 0;
}

0 0
原创粉丝点击