例如,圖(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;
}
運行結果如下: