《劍指offer》:[60]把二叉樹列印成多行
阿新 • • 發佈:2019-01-01
題目:從上到下安層列印二叉樹,同一層的結點按從左到右的順序列印,每一層列印一行。
具體實現程式碼如下:
例如,圖(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;//下一層的結點數; 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;//一行列印完了,所以換行; tobePrinted=nextlevel; nextlevel=0; } } } int main() { CreateTree(pRoot1); cout<<"之字形列印如下:"<<endl; PrintTree(pRoot1); cout<<endl; system("pause"); return 0; }
執行結果如下: