二叉树逐层遍历
依靠一个队列先进后出的特点进行算法设计如下:
<span style="font-size:18px;">void BinaryTreeTraversal(const BinaryTreeNode* head)
{
if(head==NULL)
return;
Queue<BinaryTreeNode*> queue;
queue.push(head);
while (queue.size()!=0)
{
BinaryTreeNode* aNode = queue.pop();
//打印aNode;
if(aNode->left)
queue.push(aNode->left);
if(aNode->right)
queue.push(aNode->right);
}
}</span>
void BinaryTreeTraversal(const BinaryTreeNode* head)
{
if(head==NULL)
return;
int cerrentLevelNodeNum=0;
Queue<BinaryTreeNode*> queue;
queue.push(head);
cerrentLevelNodeNum=queue.size();
while (queue.size()!=0)
{
//更新cerrentLevelNodeNum
if(cerrentLevelNodeNum==0)
{
cerrentLevelNodeNum=queue.size();
}
BinaryTreeNode* aNode = queue.pop();
//这里打印输出aNode节点信息
cerrentLevelNodeNum--;
if(cerrentLevelNodeNum==0)
{
//打印换行符
}
if(aNode->left)
queue.push(aNode->left);
if(aNode->right)
queue.push(aNode->right);
}
}