统计并保存叶子节点(二叉树)

输出

 按从上到下从左到右的顺序输出二叉树的叶子结点。

示例输入

abd,,eg,,,cf,,,
xnl,,i,,u,,

示例输出

dfg
uli

就是一个二叉树的层次遍历.但WA4次因为直接输出的leave数组,要用for(;i<ans;)控制一下.

#include <iostream>
#include <algorithm>
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <queue>
#include <cmath>
#define inf 0x3f3f3f3f;
#define ls l,mid,rt<<1
#define rs mid+1,r,rt<<1|1
#define maxn 50000
using namespace std;
char s[maxn];
int tmp,ans;
struct node
{
    char c;
    node *l,*r;
};
char p,leave[maxn];
queue<node *>Q;
node *bu(node *rt)
{
    rt=new node;
    p=s[tmp++];
    if(p==',')
        rt=NULL;
    else
    {
        rt->c=p;
        rt->l=bu(rt->l);
        rt->r=bu(rt->r);
    }
    return rt;
}
void look(node *rt)
{
    if(rt!=NULL)
        Q.push(rt);
    while(!Q.empty())
    {
        node *a;
        a=Q.front();
        Q.pop();
        if( (!a->l)&&(!a->r))
            leave[ans++]=a->c;
        if(a->l)
            Q.push(a->l);
        if(a->r)
            Q.push(a->r);
    }
}
int main()
{
    int n,m,i,j,k;
    while(~scanf("%s",s))
    {
        while(!Q.empty())
            Q.pop();
        ans=0;tmp=0;
        node *rt;
        rt=new node;
        rt=bu(rt);
        look(rt);
        for(i=0;i<ans;i++)
            printf("%c",leave[i]);
        printf("\n");
    }
    return 0;
}


你可能感兴趣的:(二叉树)