您的位置:首页 > 理论基础 > 数据结构算法

数据结构实验之二叉树七:叶子问题

2016-08-08 15:44 302 查看
题目链接

#include<iostream>
#include<algorithm>
#include<string>

using namespace std;

string a;
int l1;

typedef struct node
{
char data;
struct node *lchild,*rchild;
}Tree;

Tree *creat()///先序建立二叉树
{
Tree *root;
char c;
c=a[l1++];
if(c==',')
return NULL;
else
{
root=new node;
root->data=c;
root->lchild=creat();
root->rchild=creat();

}
return root;
}
void leave(Tree *root)///借助队列从左到右从上到下输出叶子节点
{
int rear=0, frot=0;
Tree *q[1010];
if(root==NULL)
return;
q[rear++]=root;
while(frot<rear)
{
root=q[frot++];
if(root->lchild==NULL&&root->rchild==NULL)
{
cout<<root->data;
}
if(root->lchild)
q[rear++]=root->lchild;
if(root->rchild)
q[rear++]=root->rchild;
}
}
int main()
{
ios::sync_with_stdio(false);
Tree *root;
while(cin>>a)
{
l1=0;
root=creat();
leave(root);
cout<<endl;
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: