面试题32 - III. 从上到下打印二叉树 III

题目:

 

 

解答:

 1 /**
 2  * Definition for a binary tree node.
 3  * struct TreeNode {
 4  *     int val;
 5  *     TreeNode *left;
 6  *     TreeNode *right;
 7  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 8  * };
 9  */
10 class Solution {
11 public:
12     vector<vector<int>> levelOrder(TreeNode* root) 
13      {
14         vector<vector<int>> res;
15 
16         if (NULL == root)
17         {
18             return res;
19         }
20 
21         queue<TreeNode*> q;
22         q.push(root);
23         int count = 1;
24         int level = 0;
25         int flag = 0;
26         
27         vector<int> tmp;
28 
29         while (!q.empty())
30         {
31             tmp.clear();        
32             level = 0;
33 
34             for (int i = 0; i < count; i++)
35             {
36                 TreeNode *root = q.front();
37                 q.pop();
38                 tmp.push_back(root->val);
39 
40                 if (root->left)
41                 {
42                     q.push(root->left);
43                     level++;
44                 }
45                 if (root->right)
46                 {
47                     q.push(root->right);
48                     level++;
49                 }
50             }
51             
52             count = level;
53             
54             if (flag % 2 == 1)
55             {
56                 reverse(tmp.begin(), tmp.end());
57             }
58             flag++;
59 
60             res.push_back(tmp);
61         }
62 
63         return res;
64     }
65 };

 

posted @ 2020-05-09 15:41  梦醒潇湘  阅读(136)  评论(0)    收藏  举报