题目大意:倒序层次遍历二叉树,先遍历最后一层,然后依次向上
分析:bfs遍历放入队列中,遍历时将每一层放入一个数组里,最后翻转数组即可。注意我们要用到的每层的结点个数就是开始遍历该层时的队列元素个数,当for循环里面压入节点后size是会发生变化的。
代码:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<vector<int>> levelOrderBottom(TreeNode* root) {
vector<vector<int>> ans;
if(!root) return ans;
queue<TreeNode*> q;
q.push(root);
while(!q.empty()){
vector<int> tmp;
int size = q.size();
for(int i = 0;i < size;i++){
TreeNode* node = q.front();
tmp.push_back(node->val);
q.pop();
if(node->left) q.push(node->left);
if(node->right) q.push(node->right);
}
ans.push_back(tmp);
}
reverse(ans.begin(),ans.end());
return ans;
}
};