题目描述
已知一个按先序输入的字符序列,如abd,,eg,,,cf,,,(其中,表示空结点)。请建立该二叉树并按从上到下从左到右的顺序输出该二叉树的所有叶子结点。
输入
输出
示例输入
abd,,eg,,,cf,,,
xnl,,i,,u,,
示例输出
dfguli
#include<stdio.h> #include<string.h> #include<stdlib.h> typedef char element; typedef struct BNode { element data; BNode *lchild,*rchild; }*BiTree; typedef struct QNode { BiTree data; QNode *next; }*queueptr; typedef struct { queueptr front; queueptr rear; }queue; char str[55]; int i; element CreateBiTree(BiTree &T)//生成树; { if(str[i++]==',') T=NULL;//树空; else { T=new struct BNode; if(!T) exit(0); T->data=str[i-1]; CreateBiTree(T->lchild);//建左子树 CreateBiTree(T->rchild);//建右子树; } return 1; } void initqueue(queue &Q)//队列的初始化; { Q.front=Q.rear=(queueptr)malloc(sizeof(QNode)); if(!Q.front) exit(0); Q.front->next=NULL; } void Enqueue(queue &Q,BiTree &e)//e前一定要加取地址符,否则死循环 {//从队尾进队相当建顺序链表; queueptr p; p=(queueptr)malloc(sizeof(QNode)); if(!p) exit(0); p->data=e; p->next=NULL; Q.rear->next=p; Q.rear=p; } element Dequeue(queue &Q,BiTree &e)//e前一定要加取地址符,否则死循环 {//从队头出队; queueptr p; if(Q.front==Q.rear) return 0; p=Q.front->next; e=p->data; Q.front->next=p->next; if(Q.rear==p)//只剩一个元素时; Q.rear=Q.front; free(p); return 1; } int Emptyqueue(queue &Q)//清空队; { if(Q.front==Q.rear) return 0; return 1; } void Traverse(BiTree &T)//浏览树的每个节点,进而判断树的叶子; { queue Q; initqueue(Q); if(T) Enqueue(Q,T); while(Emptyqueue(Q)) { Dequeue(Q,T); if(!T->lchild&&!T->rchild)//叶子结点判定条件 printf("%c",T->data); if(T->lchild) Enqueue(Q,T->lchild); if(T->rchild) Enqueue(Q,T->rchild); } } int main() { BiTree T; while(~scanf("%s",str)) { i=0; CreateBiTree(T);//生成树; Traverse(T);//树叶子的遍历; printf("\n"); } }
#include<iostream> #include<cstring> #include<queue> #include<cstdio> #include<algorithm> using namespace std; typedef struct Bnode { char data; Bnode *rchild,*lchild; }*BiTree,Bnode; char str[55]; int i; void create(BiTree &T) { if(str[i++]==',') T=NULL; else { T=new Bnode; if(!T) exit(0); T->data=str[i-1]; create(T->lchild); create(T->rchild); } } void cengci(BiTree &T) { int out=0,in=0; BiTree q[100];//存树的队列; if(T) q[in++]=T; while(in>out) { if(q[out]) { printf("%c",q[out]->data); q[in++]=q[out]->lchild; q[in++]=q[out]->rchild; } out++; } } void Traverse(BiTree T) { queue<BiTree> q; BiTree p=NULL; if(T) { q.push(T); } while(!q.empty()) { p=q.front(); q.pop(); if(!p->lchild&&!p->rchild) cout<<p->data; if(p->lchild) q.push(p->lchild); if(p->rchild) q.push(p->rchild); } } int main() { BiTree T; while(~scanf("%s",str)) { T=NULL; i=0; create(T); //cengci(T); Traverse(T); cout<<endl; } return 0; }