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

题目:

 

 

解答:

 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<int> levelOrder(TreeNode* root) 
13     {
14         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         
26         while (!q.empty())
27         {
28             level = 0;
29             for (int i = 0; i < count; i++)
30             {
31                 TreeNode *tmp = q.front();
32                 q.pop();
33                 res.push_back(tmp->val);
34 
35                 if (tmp->left)
36                 {
37                     q.push(tmp->left);
38                     level++;
39                 }
40                 if (tmp->right)
41                 {
42                     q.push(tmp->right);
43                     level++;
44                 }
45             }
46 
47             count = level;
48         }
49 
50         return res;
51     }
52 };

 

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