加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > PHP教程 > 正文

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

发布时间:2020-12-13 21:12:40 所属栏目:PHP教程 来源:网络整理
导读:题目:从上到下安层打印2叉树,同1层的结点按从左到右的顺序打印,每层打印1行。 例如,图(1)中2叉树和打印结果为: 这个题其实很简单,我们只需要设置两个变量就能够弄定。1个变量表示当前层中还没有打印的结点数,另外一个变量表示下1层结点的数目。 具
题目:从上到下安层打印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; }

运行结果以下:





(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读