#include <stdio.h>
#include <stdlib.h>
#include <queue>
#include <iostream>
using namespace std;
char s[101];
struct Node
{
char data;
struct Node * lchild,* rchild;
};
struct Node * root;
int cnt;
//构造二叉树
struct Node * Build_tree()
{
struct Node * root;
if(s[cnt++] == ',') root = NULL;
else
{
root = (struct Node *)malloc(sizeof(struct Node));
root -> data = s[cnt - 1];
root -> lchild = Build_tree();
root -> rchild = Build_tree();
}
return root;
}
void cengcibianli(Node *root) //层次遍历
{
queue<Node*>s;
if(root)
{
printf("%c", root->data);
s.push(root);
while(!s.empty())
{
root = s.front();
s.pop();
if(root->lchild)
{
printf("%c", root->lchild->data);
s.push(root->lchild);
}
if(root->rchild)
{
printf("%c", root->rchild->data);
s.push(root->rchild);
}
}
}
}
int main()
{
int n;
cin>>n;
while(n--)
{
scanf("%s",s);
cnt = 0;
root = Build_tree(); //建树
cengcibianli(root);
cout<<endl;
}
return 0;
}
数据结构实验之二叉树五:层序遍历
最新推荐文章于 2019-01-24 20:17:42 发布