标签:
题目:从上到下安层打印二叉树,同一层的结点按从左到右的顺序打印,每一层打印一行。例如,图(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;
}
运行结果如下:
标签:
原文地址:http://blog.csdn.net/gogokongyin/article/details/51778388