题目:从上到下按层打印二叉树,同一层的结点按从左到右的顺序打印,每一层打印到一行。
思路:实质是考察树的按层遍历算法,应该利用队列先入先出的特性来完成打印。每次打印一个节点的时候,如果该节点有子节点,则把该节点的子节点放到队列的末尾;接下来到队列的头部取出最早进入队列的节点,重复前面的打印操作,直到队列中所有的节点都被打印出来。为了把二叉树的每一行单独打印到一行里,需要两个变量:nextLevel表示在当前层中还没有打印的节点数目;toBePrinted表示下一层的节点数目。
核心代码如下:
struct BinaryTreeNode{
int m_nValue;
BinaryTreeNode* m_pLeft;
BinaryTreeNode* m_pRight;
};
void Print(BinaryTreeNode* pTreeRoot){
if(!pTreeRoot)
return;
queue<BinaryTreeNode*> nodes;
nodes.push(pTreeRoot);
int nextLevel = 0; //表示在当前层中还没有打印的节点数目
int toBePrinted = 1; //表示下一层的节点数目
while(!nodes.empty()){
BinaryTreeNode* pNode = nodes.front();
cout << 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){ //分行打印操作
cout << endl;
toBePrinted = nextLevel;
nextLevel = 0;
}
}
}