题目:分行从上到下打印二叉树
从上到下按层打印二叉树,同一层的节点按从左到右的顺序打印,每一层打印到一行。
思路:为了把二叉树的每一行单独打印到一行里,我们需要两个变量:一个变量表示在当前层还没有打印的节点数;另一个变量表示下一层节点的数目。
代码实现如下:
struct BinaryTreeNode{
int m_nValue;
BinaryTreeNode* m_pLeft;
BinaryTreeNode* m_Right;
}
void Print(BinaryTreeNode* pRoot){
if(pRoot == nullptr)
return;
std::queue<BinaryTreeNode*> nodes;
nodes.push(pRoot);
//表示下一层的节点数
int nextLevel = 0;
//表示当前层中还没有打印的节点数
int toBePrinted = 1;
while(!nodes.empty()){
BinaryTreeNode* pNode = nodes.front();
printf("%d ",pNode->m_nvalue);
if(pNode->m_pLeft != nullptr){
nodes.push(pNode->m_pLeft);
++nextLevel;
}
if(pNode->m_pRight != nullptr){
nodes.push(pNode->m_pRight);
++nextLevel;
}
nodes.pop();
--toBePrinted;
if(toBePrinted == 0){
printf("\n");
toBePrinted = nextLevel;
nextLevel = 0;
}
}
}