数据结构实验之二叉树五:层序遍历
2016-08-08 15:05
465 查看
借助队列实现
题目链接
#include<string>
#include<iostream>
#include<algorithm>
using namespace std;
string a;
int l1;
typedef struct node
{
char data;
struct node *lchild,*rchild;
}Tree;
struct node *creat()///先序建立二叉树
{
Tree *root;
char c;
c=a[l1++];
if(c==',')
return NULL;
else
{
root=new Tree;
root->data=c;
root->lchild=creat();
root->rchild=creat();
}
return root;
}
void intree(Tree *root)
{
if(root!=NULL)
{
intree(root->lchild);
cout<<root->data;
intree(root->rchild);
}
}
void lastree(Tree *root)
{
if(root!=NULL)
{
lastree(root->lchild);
lastree(root->rchild);
cout<<root->data;
}
}
void arrantree(Tree *root)
{
Tree *p[1010];
int rear=0, frot=0;
if(root)
{
cout<<root->data;
p[rear++]=root;
}
while(rear>frot)
{
root=p[frot++];
if(root->lchild)
{
cout<<root->lchild->data;
p[rear++]=root->lchild;
}
if(root->rchild)
{
cout<<root->rchild->data;
p[rear++]=root->rchild;
}
}
}
int leave(struct node *root)///统计叶子数
{
if(root==NULL)
return 0;
if(root->lchild==NULL&&root->rchild==NULL)
return 1;
else
return leave(root->lchild)+leave(root->rchild);
}
int main()
{
ios::sync_with_stdio(false);
Tree *root;
int t;
cin>>t;
while(t--)
{
cin>>a;
l1=0;
root=creat();
arrantree(root);
cout<<endl;
}
return 0;
}
题目链接
#include<string>
#include<iostream>
#include<algorithm>
using namespace std;
string a;
int l1;
typedef struct node
{
char data;
struct node *lchild,*rchild;
}Tree;
struct node *creat()///先序建立二叉树
{
Tree *root;
char c;
c=a[l1++];
if(c==',')
return NULL;
else
{
root=new Tree;
root->data=c;
root->lchild=creat();
root->rchild=creat();
}
return root;
}
void intree(Tree *root)
{
if(root!=NULL)
{
intree(root->lchild);
cout<<root->data;
intree(root->rchild);
}
}
void lastree(Tree *root)
{
if(root!=NULL)
{
lastree(root->lchild);
lastree(root->rchild);
cout<<root->data;
}
}
void arrantree(Tree *root)
{
Tree *p[1010];
int rear=0, frot=0;
if(root)
{
cout<<root->data;
p[rear++]=root;
}
while(rear>frot)
{
root=p[frot++];
if(root->lchild)
{
cout<<root->lchild->data;
p[rear++]=root->lchild;
}
if(root->rchild)
{
cout<<root->rchild->data;
p[rear++]=root->rchild;
}
}
}
int leave(struct node *root)///统计叶子数
{
if(root==NULL)
return 0;
if(root->lchild==NULL&&root->rchild==NULL)
return 1;
else
return leave(root->lchild)+leave(root->rchild);
}
int main()
{
ios::sync_with_stdio(false);
Tree *root;
int t;
cin>>t;
while(t--)
{
cin>>a;
l1=0;
root=creat();
arrantree(root);
cout<<endl;
}
return 0;
}
相关文章推荐
- SDUT 3344 数据结构实验之二叉树五:层序遍历
- 数据结构实验之二叉树五:层序遍历
- 数据结构实验之二叉树五:层序遍历
- 3344-->数据结构实验之二叉树五:层序遍历
- 数据结构实验之二叉树五:层序遍历*(层序遍历要学好
- 数据结构实验之二叉树五:层序遍历
- 数据结构实验之二叉树五:层序遍历
- 3344---数据结构实验之二叉树五:层序遍历
- 数据结构实验之二叉树五:层序遍历
- 3346--数据结构实验之二叉树五:层序遍历
- 数据结构实验之二叉树五:层序遍历(数组模拟队列)
- SDUT OJ 数据结构实验之二叉树五:层序遍历
- 暑假集训 8.8-2 sdut3344 数据结构实验之二叉树五:层序遍历
- sdutacm-数据结构实验之二叉树五:层序遍历
- 数据结构实验之二叉树五:层序遍历
- 数据结构实验之二叉树五:层序遍历
- 数据结构实验之二叉树五:层序遍历
- 数据结构实验之二叉树五:层序遍历
- 数据结构实验之二叉树五:层序遍历
- 数据结构实验之二叉树五:层序遍历