《劍指offer》:[60]把二叉樹打印成多行
來源:程序員人生 發布時間:2016-08-02 08:48:43 閱讀次數:2438次
題目:從上到下安層打印2叉樹,同1層的結點按從左到右的順序打印,每層打印1行。
例如,圖(1)中2叉樹和打印結果為:

這個題其實很簡單,我們只需要設置兩個變量就能夠弄定。1個變量表示當前層中還沒有打印的結點數,另外一個變量表示下1層結點的數目。
具體實現代碼以下:
#include <iostream>
#include <queue>
using namespace std;
struct BinaryTree
{
int data;
BinaryTree *pLeft;
BinaryTree *pRight;
};
BinaryTree *pRoot1=NULL;
queue<BinaryTree *> node;
void CreateTree(BinaryTree *&root)
{
int data;
cin>>data;
if(0==data)
root=NULL;
else
{
root=new BinaryTree;
root->data=data;
CreateTree(root->pLeft);
CreateTree(root->pRight);
}
}
void PrintTree(BinaryTree *root)
{
if(NULL==root)
return;
node.push(root);
int nextlevel=0;//下1層的結點數;
int tobePrinted=1;//當前還有幾個結點;
while(!node.empty())
{
BinaryTree *pNode=node.front();
cout<<pNode->data<<" ";
if(pNode->pLeft!=NULL)
{
node.push(pNode->pLeft);
nextlevel++;
}
if(pNode->pRight!=NULL)
{
node.push(pNode->pRight);
nextlevel++;
}
node.pop();//入隊列的速度比出隊列的要快;
tobePrinted--;
if(tobePrinted==0)
{
cout<<endl;//1行打印完了,所以換行;
tobePrinted=nextlevel;
nextlevel=0;
}
}
}
int main()
{
CreateTree(pRoot1);
cout<<"之字形打印以下:"<<endl;
PrintTree(pRoot1);
cout<<endl;
system("pause");
return 0;
}
運行結果以下:

生活不易,碼農辛苦
如果您覺得本網站對您的學習有所幫助,可以手機掃描二維碼進行捐贈