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

這個(gè)題其實(shí)很簡單,我們只需要設(shè)置兩個(gè)變量就能夠弄定。1個(gè)變量表示當(dāng)前層中還沒有打印的結(jié)點(diǎn)數(shù),另外一個(gè)變量表示下1層結(jié)點(diǎn)的數(shù)目。
具體實(shí)現(xiàn)代碼以下:
#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層的結(jié)點(diǎn)數(shù);
int tobePrinted=1;//當(dāng)前還有幾個(gè)結(jié)點(diǎn);
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();//入隊(duì)列的速度比出隊(duì)列的要快;
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;
}
運(yùn)行結(jié)果以下:

生活不易,碼農(nóng)辛苦
如果您覺得本網(wǎng)站對您的學(xué)習(xí)有所幫助,可以手機(jī)掃描二維碼進(jìn)行捐贈(zèng)