107. 二叉树的层次遍历 II

 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 {
12     vector<vector<int>> ans;
13 public:
14     vector<vector<int>> levelOrderBottom(TreeNode* root) 
15     {
16         if(!root) return ans;
17         queue<TreeNode*> q;
18         q.push(root);
19         while(!q.empty())
20         {
21             int n = q.size();
22             vector<int> temp;
23             for(int i = 0;i < n;i ++)
24             {
25                 TreeNode* t = q.front();
26                 q.pop();
27                 temp.push_back(t->val);
28                 if(t->left) q.push(t->left);
29                 if(t->right) q.push(t->right);
30             }
31             ans.push_back(temp);
32         }
33         reverse(ans.begin(),ans.end());
34         return ans;
35     }
36 };

 

posted @ 2020-04-01 13:26  Jinxiaobo0509  阅读(96)  评论(0)    收藏  举报