题目:
从上到下按层打印二叉树,同一层的结点按从左到右的顺序打印,每一层打印到一行。
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;
}
}
}