/**
* 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) return res;
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();
q.pop();
tmp.push_back(node->val);
if(node->left) q.push(node->left);
if(node->right) q.push(node->right);
}
res.insert(res.begin(), tmp);
}
return res;
}
};
for循环处不能用q.size(),必须在之前保存下q的size,以为q的大小在变化
LeetCode 107
最新推荐文章于 2021-10-29 23:36:07 发布