Disclaimer: This article is a blogger original article, shall not be reproduced without the bloggers allowed. https://blog.csdn.net/gjh13/article/details/90740002
Problem-solving ideas:
Queues implemented using binary tree traversal sequence, as in claim val title stored in each layer in a vector, so the inner loop, but also a queue for storing each update node layer.
At the end, we need to get the res array in reverse order.
/**
* 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) {
if(!root) return {};
vector<vector<int> > res;
queue<TreeNode*> q;
q.push(root);
while(!q.empty()){
vector<int> tmp;
queue<TreeNode*> tmpq;
while(!q.empty()){
TreeNode* t = q.front();
q.pop();
tmp.push_back(t->val);
if(t->left) tmpq.push(t->left);
if(t->right) tmpq.push(t->right);
}
res.push_back(tmp);
q = tmpq;
}
reverse(res.begin(), res.end());
return res;
}
};