层次遍历,本来一个循环就可以,但是要输出一个二位数组,就变成嵌套循环了。
然后把结果逆序一下就可以了。
class Solution {
public:
vector<vector<int>> levelOrderBottom(TreeNode* root) {
vector<vector<int>> res;
if(!root) return res;
queue<TreeNode*> que;
que.push(root);
while(que.size()!=0){
vector<int> tmpRes;
queue<TreeNode*> tmpQue;
while(que.size()!=0){
TreeNode *node = que.front();
que.pop();
if(node->left) tmpQue.push(node->left);
if(node->right) tmpQue.push(node->right);
tmpRes.push_back(node->val);
}
res.push_back(tmpRes);
que = tmpQue;
}
reverse(res.begin(),res.end());
return res;
}
};