您的位置:首页 > Web前端

剑指offer-把二叉树打印成多行

2017-08-25 09:47 369 查看
题目:

从上到下按层打印二叉树,同一层的结点按从左到右的顺序打印,每一层打印到一行。

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;
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: