Note:跟之前的一样,多了个reverse();
代码如下:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
vector<vector<int>> levelOrderBottom(TreeNode* root) {
vector<vector<int>> ans;
vector<int> path;
vector<TreeNode*> q;
if(!root) return ans;
q.push_back(root);
int last = 0, f = -1, t = 0;
while(f < t){
auto node = q[++ f];
path.push_back(node -> val);
if(node -> left) q.push_back(node -> left), t ++;
if(node -> right) q.push_back(node -> right), t ++;
if(f == last){
ans.push_back(path);
last = t;
path.clear();
}
}
reverse(ans.begin(), ans.end());
return ans;
}
};