给你二叉树的根节点 root
,返回其节点值 自底向上的层序遍历 。 (即按从叶子节点所在层到根节点所在的层,逐层从左向右遍历)
示例 1:
输入:root = [3,9,20,null,null,15,7] 输出:[[15,7],[9,20],[3]]
示例 2:
输入:root = [1] 输出:[[1]]
示例 3:
输入:root = [] 输出:[]
/**
* 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>>res;
vector<vector<int>> levelOrderBottom(TreeNode* root) {
if(root==nullptr)return res;
queue<TreeNode *> s;
s.push(root);
while(!s.empty())
{
vector<int>path;
int len=s.size();
for(int i=0;i<len;i++)
{
TreeNode * p=s.front();
s.pop();
path.push_back(p->val);
if(p->left)s.push(p->left);
if(p->right)s.push(p->right);
}
res.push_back(path);
}
std::ranges::reverse(res);
return res;
}
};