首页 > 其他 > 详细

60、剑指offer--把二叉树打印成多行

时间:2017-07-04 10:43:04      阅读:261      评论:0      收藏:0      [点我收藏+]
题目描述
从上到下按层打印二叉树,同一层结点从左至右输出。每一层输出一行。
 
解题思路:可以直到,每次打印一个结点,然后打印下一行时总是先打印其左子结点,然后打印其右子结点。先入先出,使用队列处理。使用toBeprint记录当前行打印的个数,每存入一个-1;nextlevel记录下一行打印结点个数;一行打印完,toBeprint = nextlevel;nextlevel = 0;
 1 /*
 2 struct TreeNode {
 3     int val;
 4     struct TreeNode *left;
 5     struct TreeNode *right;
 6     TreeNode(int x) :
 7             val(x), left(NULL), right(NULL) {
 8     }
 9 };
10 */
11 class Solution {
12 public:
13         vector<vector<int> > Print(TreeNode* pRoot) {
14             vector<vector<int> > result;
15             vector<int> temp;//间接变量,存储一行
16             if(pRoot == NULL)
17                 return result;
18             queue<TreeNode *> nodes;
19             nodes.push(pRoot);
20             int nextlevel = 0;//下一行应打印个数
21             int toBePrint = 1;//当前行剩余打印个数
22             while(!nodes.empty())
23             {
24                 TreeNode *pNode = nodes.front();
25                 temp.push_back(pNode->val);
26                 if(pNode->left != NULL)
27                 {
28                     nodes.push(pNode->left);
29                     ++nextlevel;
30                 }
31                 if(pNode->right != NULL)
32                 {
33                     nodes.push(pNode->right);
34                     ++nextlevel;
35                 }
36                 nodes.pop();
37                 --toBePrint;
38                 if(toBePrint == 0)//一行已打印完
39                 {
40                     result.push_back(temp);
41                     temp.clear();//清空
42                     toBePrint = nextlevel;
43                     nextlevel = 0;
44                 }
45             }
46             return result;
47         }
48 };

 

60、剑指offer--把二叉树打印成多行

原文:http://www.cnblogs.com/qqky/p/7115314.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!