之所以记录下这题,是因为找一个奇怪的问题好久,见注释
/**
* 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>> res;
if(root == nullptr)
return res;
queue<TreeNode*> q;
q.push(root);
while(!q.empty()){
vector<int> temp;
int len = q.size();
//必须先获取队列大小
//注意这里不能写成for(int i=0;i<q.size();i++)运行结果不正确,
//要么就写成for(int i=q.size();i>0;i--)
for(int i = 0; i < len; i ++){
TreeNode* node = q.front();
q.pop();
temp.push_back(node->val);
if(node->left){
q.push(node->left);
}
if(node->right){
q.push(node->right);
}
}
res.push_back(temp);
}
reverse(res.begin(), res.end());
return res;
}
};