You have a binary tree. Print node values starting from the root going level by level, i.e. first line has root node's value, second line has two child node's values, third line - left and right child nodes values of the root's left child then left and right child nodes values of the root's right child, and so on.
#include <iostream>
#include <queue>
struct node
{
int data;
node* left;
node* right;
node(int _data, node* _left, node* _right)
{
data = _data;
left = _left;
right = _right;
}
};
int main()
{
node* n7 = new node(7, NULL, NULL);
node* n6 = new node(6, NULL, NULL);
node* n5 = new node(5, NULL, NULL);
node* n4 = new node(4, NULL, NULL);
node* n3 = new node(3, n6, n7);
node* n2 = new node(2, n4, n5);
node* n1 = new node(1, n2, n3);
node* root = n1;
std::queue<node*> q;
q.push(root);
q.push(NULL);
while(!q.empty())
{
node* cur = q.front();
if(cur != NULL)
{
printf("%d ", cur->data);
q.pop();
if(cur->left != NULL)
q.push(cur->left);
if(cur->right != NULL)
q.push(cur->right);
}
else
{
if(q.size() == 1)
break;
else
{
q.pop();
q.push(NULL);
printf("\n");
}
}
}
return 0;
}
本文介绍如何使用C++实现二叉树的层次遍历,从根节点开始,逐层打印每个节点的值。
1094

被折叠的 条评论
为什么被折叠?



