数据结构实验之二叉树五:层序遍历

来源:互联网 发布:php 读取本地图片 编辑:程序博客网 时间:2024/06/14 02:26

Problem Description

已知一个按先序输入的字符序列,如abd,,eg,,,cf,,,(其中,表示空结点)。请建立二叉树并求二叉树的层次遍历序列。

Input

 输入数据有多行,第一行是一个整数t (t<1000),代表有t行测试数据。每行是一个长度小于50个字符的字符串。

Output

 输出二叉树的层次遍历序列。

Example Input

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

Example Output

abcdefgxnuli

    层序遍历借助了队列这种结构,先将根节点加入队列,在循环中每次都将队首的节点移出,同时将队首节点的左右子节点加入队列中,直到队列为空。

#include <iostream>#include <queue>#include <string>using namespace std;char s[55];int pos = -1;struct node{char data;node *l,*r;};struct node *creat(){node *t;if(s[++pos] == ',')return NULL;t = new node;t->data = s[pos];t->l = creat();t->r = creat();return t;}void levelshow(struct node *t){queue<node *>Q;node *temp;Q.push(t);while(!Q.empty()){temp = Q.front();Q.pop();if(temp){cout<<temp->data;Q.push(temp->l);Q.push(temp->r);}}}int main(int argc, char const *argv[]){node *root;int t;cin>>t;while(t--){pos = -1;cin>>s;root = creat();levelshow(root);cout<<endl;}return 0;}


 
原创粉丝点击