题目:
从上到下按层打印二叉树,同一层的结点按从左到右的顺序打印,每一层打印到一行。
struct BinaryTree
{
int data;
BinaryTree *left;
BinaryTree *right;
};
void print(BinaryTree *pRoot)
{
if (pRoot == NULL)
return;
queue <BinaryTree *> nodes;
nodes.push(pRoot);
int toBePrint = 1;//记录该行要打印数据;
int nextLevel = 0;//下一行要打印数据;
while (!nodes.empty())
{
BinaryTree *pNode = nodes.front();
cout << pNode->data;
if (pNode->left != NULL)
{
nodes.push(pNode->left);
++nextLevel;
}
if (pNode->right != NULL)
{
nodes.push(pNode->right);
++nextLevel;
}
nodes.pop();//弹出队列
--toBePrint;
if (toBePrint == 0)
{
cout << endl;
toBePrint = nextLevel;
nextLevel = 0;
}
}
}
本文介绍了一种按层打印二叉树的方法,通过使用队列实现从上到下、从左到右的层次遍历,并将每层的节点值打印在一行中。
231

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



