看到这个题目标了三颗星,觉得挺奇怪的,这个题应该跟层序遍历二叉树差不多。
把教材上的层序遍历改了改,多加了一个指针,指向当前层的最后一个位置。
其实跟编程之美的最后一段代码基本一样,只是改用数组实现的顺序队列。
代码:
void LevelOrder(Node* root) //每层末尾输出换行
{
if(!root) return;
Node* q[TREELEN]; //队列
int front = -1; //对首元素的前一个位置
int rear = -1; //当前层最后一个结点的位置
int cur = -1; //队尾元素位置
q[++cur] = root;
rear++;
while(front != cur)
{
while(front<rear)
{
root = q[++front];
cout<<root->chValue<<" ";
if(root->pLeft) q[++cur] = root->pLeft;
if(root->pRight) q[++cur] = root->pRight;
}
cout<<endl;
rear = cur;
}
}