107. 二叉树的层次遍历 II - 力扣(LeetCode)
和这个很像:
LeetCode第 102 题:二叉树的层次遍历(C++)_qq_32523711的博客-CSDN博客
最后加一个反转容器就可以啦:
class Solution {
public:
vector<vector<int>> levelOrderBottom(TreeNode* root) {
vector<vector<int>> vec;
if(!root) return vec;
queue<TreeNode*> q;
q.push(root);
while(!q.empty()){
int len = q.size();
vector<int> level;
for(int i = 0; i < len; ++i){
auto tmp = q.front();
q.pop();
level.push_back(tmp->val);
if(tmp->left) q.push(tmp->left);
if(tmp->right) q.push(tmp->right);
}
vec.push_back(level);
}
reverse(vec.begin(), vec.end());
return vec;
}
};