题目
从上往下打印出二叉树的每个结点,同一层的结点按照从左到右的顺序打印。
思路
代码
#include <iostream>
#include <queue>
using namespace std;
struct BinaryTreeNode
{
int value;
BinaryTreeNode* p_left;
BinaryTreeNode* p_right;
};
void PrintTree(BinaryTreeNode *pTreeRoot)
{
if (!pTreeRoot)
return;
queue<BinaryTreeNode *> queNode;
queNode.push(pTreeRoot);
while (!queNode.empty())
{
BinaryTreeNode *pNode = queNode.front();
queNode.pop();
cout << pNode->value << " ";
if (pNode->p_left)
queNode.push(pNode->p_left);
if (pNode->p_right)
queNode.push(pNode->p_right);
}
}
int main()
{
queue<BinaryTreeNode> data;
BinaryTreeNode n1{5, nullptr, nullptr};
BinaryTreeNode n2{7, nullptr, nullptr};
BinaryTreeNode n3{9, nullptr, nullptr};
BinaryTreeNode n4{11, nullptr, nullptr};
BinaryTreeNode n5{6, &n1, &n2};
BinaryTreeNode n6{10, &n3, &n4};
BinaryTreeNode n7{8, &n5, &n6};
PrintTree(&n7);
return EXIT_SUCCESS;
}