c++二叉树遍历模板

                         请根据题目实际情况选择函数调用

#include 
using namespace std;
#define INF 0x3f3f3f3f
typedef struct node{///结构体
char data;
node *l,*r;
}tree ;
char shu[55];///有','的输入数组
int q,cnt,sum;
tree *creat(char *xian,char *zhong,int len){///先序中序建二叉树
    tree *t=new tree;
    if(len<=0)return NULL;
    t->data=*xian;
    char *p;
    for(p=zhong;pl=creat(xian+1,zhong,k);
    t->r=creat(xian+k+1,p+1,len-k-1);
    return t;
}

tree *rcreat(char *zhong,char *hou,int len){///中序后序建二叉树
    tree *t=new tree;
    if(len<=0)return NULL;
    t->data=*(hou+len-1);
    char *p;
    for(p=zhong;pl=rcreat(zhong,hou,k);
    t->r=rcreat(zhong+k+1,hou+k,len-k-1);
return t;
}

tree *_creat(tree *t){///带','建二叉树
    t=new tree;
    char x=shu[q++];
    if(x==',')t=NULL;
    else {
        t->data=x;
        t->l=_creat(t->l);
        t->r=_creat(t->r);
    }
return t;
}

void xianxu(tree *t){///先序遍历
if(t){
    cout<data;
    xianxu(t->l);
    xianxu(t->r);
}
}

void zhongxu(tree *t){///中序遍历
if(t){
    zhongxu(t->l);
    cout<data;
    zhongxu(t->r);
}
}

void houxu(tree *t){///后序遍历
if(t){
    houxu(t->l);
    houxu(t->r);
    cout<data;
}
}

void bfs(tree *t){///层次遍历
    queueq;
    q.push(t);
    while(!q.empty()){
        node *temp=q.front();
        q.pop();
        if(temp){
            q.push(temp->l);
            q.push(temp->r);
            cout<data;
        }
    }
}

int yezi(tree *t){///带','的叶子节点个数
    if(t){
        if(t->l==NULL&&t->r==NULL)
            cnt++;
        yezi(t->l);
        yezi(t->r);
    }
return cnt;
}

int _yezi(tree *t){///叶子节点输出
    queueq;
    q.push(t);
    while(!q.empty()){
        t=q.front();
        q.pop();
        if(t){
            if(t->l==NULL&&t->r==NULL)
                cout<data;
            q.push(t->l);
            q.push(t->r);
        }
    }
}

int shendu(tree *t){///树深度计算
    if(t){
        int r=shendu(t->r)+1;
        int l=shendu(t->l)+1;
        return max(r,l);
    }
return 0;
}

int main(){///主函数
    ios::sync_with_stdio(0);///防止超时,可忽略
    char xian[55],zhong[55],hou[55];
    int t;
    cin>>t;
    while(t--){
        cin>>zhong>>hou;
        while(cin>>shu){
        cnt=0,q=0,sum=0;
        tree *t=new tree;
        t=_creat(t);
        _yezi(t);
        cout<

 

你可能感兴趣的:(模板)