题目描述:
给定一个二叉树,返回其节点值自底向上的层次遍历。 (即按从叶子节点所在层到根节点所在的层,逐层从左向右遍历)
例如:
给定二叉树 [3,9,20,null,null,15,7]
,
3 / \ 9 20 / \ 15 7
返回其自底向上的层次遍历为:
[ [15,7], [9,20], [3] ]
解题思路:此题跟102基本一样,就是在输出时是自底向上的,故还是可以设定一个count值来存储每层的变量数,然后依次弹出即可,最后使用vector的函数reverse函数即可。
/**
* 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>> a;
if(!root) return a;
vector<int> b;
TreeNode *temp;
queue<TreeNode*> q;
q.push(root);
int count=q.size();//用count来记每层的节点数
while(!q.empty()){
b.clear(); //每遍历完一层后清空一维数组
while(count--){
temp=q.front();
q.pop();
b.push_back(temp->val);
if(temp->left) q.push(temp->left);//将左右结点压入
if(temp->right) q.push(temp->right);
}
a.push_back(b);
count=q.size();
}
reverse(a.begin(),a.end());//反转二维数组
return a;
}
};