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

来源:互联网 发布:windows7怎样优化电脑 编辑:程序博客网 时间:2024/06/05 10:29
题目:从上到下安层打印二叉树,同一层的结点按从左到右的顺序打印,每一层打印一行。

例如,图(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;}

运行结果如下:





0 0
原创粉丝点击