按行打印二叉树

题目描述

从上到下按层打印二叉树,同一层结点从左至右输出。每一层输出一行
 
思路:维护两个指针:last和nlast,其中,last始终指向当前打印行的最后一个节点,nlast始终指向队列中最后一个节点
 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>> res;
15         if(pRoot==NULL)return res;
16         vector<int> tmp;
17         std::queue<TreeNode *> que;
18         que.push(pRoot);
19         TreeNode *last=pRoot;
20         TreeNode *nlast=pRoot;
21         while(que.size())
22         {
23             TreeNode *p=que.front();
24             que.pop();
25             tmp.push_back(p->val);
26             if(p->left)
27             {
28                 que.push(p->left);
29                 nlast=p->left;
30             }
31             if(p->right)
32             {
33                 que.push(p->right);
34                 nlast=p->right;
35             }
36             if(p==last)
37             {
38                 res.push_back(tmp);
39                 tmp.clear();
40                 last=nlast;
41             }
42         }
43         return res;
44     }
45 };

 

posted @ 2018-02-02 12:45  jeysin  阅读(173)  评论(0编辑  收藏  举报