看到這個題目标了三顆星,覺得挺奇怪的,這個題應該跟層序周遊二叉樹差不多。
把教材上的層序周遊改了改,多加了一個指針,指向目前層的最後一個位置。
其實跟程式設計之美的最後一段代碼基本一樣,隻是改用數組實作的順序隊列。
代碼:
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;
}
}