怎样从顶部开始逐层打印二叉树结点数据?请编程。
#include<iostream>
#include<queue>
#include<time.h>
using namespace std;
struct node
{
int value;
node* left;
node* right;
node(int v)
{
value = v;
left = NULL;
right = NULL;
}
};
class bintree
{
private:
node* root;
public:
bintree()
{
root = NULL;
}
void insert(int value)
{
if(root == NULL)
root = new node(value);
else
{
node* tmp = root;
node* parent = root;
int flag = 0;
while(tmp != NULL)
{
parent = tmp;
srand(time(NULL));
flag = rand() % 2;
if(flag == 1)//奇数往左边走,偶数往右边走
tmp = tmp->left;
else tmp = tmp->right;
}
node* child = new node(value);
if(flag == 1)
parent->left = child;
else parent->right = child;
}
}
void print()//逐层打印节点数据
{
if(root == NULL)
return;
queue<node*> q;
node* tmp = root;
q.push(tmp);
int count = 0;
int m = 0;
while(!q.empty())//用队列存储节点
{
cout << (q.front())->value << ' ';
node* parent = q.front();
if(parent->left != NULL)
q.push(parent->left);
if(parent->right != NULL)
q.push(parent->right);
q.pop();
}
}
};
int main()
{
int i;
bintree tree;
while(true)
{
cin >> i;
if(i == -1)
break;
tree.insert(i);
}
tree.print();
}