国内最全IT社区平台 联系我们 | 收藏本站
华晨云阿里云优惠2
您当前位置:首页 > php开源 > php教程 > 《剑指offer》:[60]把二叉树打印成多行

《剑指offer》:[60]把二叉树打印成多行

来源:程序员人生   发布时间:2016-08-02 08:48:43 阅读次数:2065次
题目:从上到下安层打印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; }

运行结果以下:





生活不易,码农辛苦
如果您觉得本网站对您的学习有所帮助,可以手机扫描二维码进行捐赠
程序员人生
------分隔线----------------------------
分享到:
------分隔线----------------------------
关闭
程序员人生