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

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

2016-07-23 16:20 369 查看
点击打开题目链接

#include <bits/stdc++.h>
using namespace std;

struct node
{
char data;
node *left, *right;
};

int i;
char str[60];
node *creat();
void levelorder(node *root);

int main()
{
int n;
cin >> n;
while(n --)
{
node *root;
scanf("%s", str);
i = 0;
root = creat();
levelorder(root);
cout << endl;
}
return 0;
}

node *creat()
{
node *tail;
if(str[i] == ',')
{
tail = NULL;
i++;
}
else
{
tail = new node;
tail -> data = str[i];
i ++;
tail -> left = creat();
tail -> right = creat();
}
return tail;
}

void levelorder(node *root)
{
queue<node *>Q;
Q.push(root);
node *tmp = new node;
while(!Q.empty())
{
tmp = Q.front();
Q.pop();
if(tmp)
{
cout << tmp -> data;
Q.push(tmp -> left);
Q.push(tmp -> right);
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  二叉树