描述
给你二叉树的根节点 root ,返回其节点值 自底向上的层序遍历 。 (即按从叶子节点所在层到根节点所在的层,逐层从左向右遍历)
示例 1:
输入:root = [3,9,20,null,null,15,7]
输出:[[15,7],[9,20],[3]]
示例 2:输入:root = [1]
输出:[[1]]
示例 3:输入:root = []
输出:[]
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/binary-tree-level-order-traversal-ii
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
题解
相对于102.二叉树的层序遍历,就是最后把result数组反转一下就可以了。
C++
/**
* 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:
void helper(vector<vector<int> >& res, TreeNode* node, int level){
if(!node) return;
if(res.size() == level) //如果是新的一层,先添加一个空vector
res.push_back({});
//将节点值存储到对应层的vector中
res[level].push_back(node->val);
helper(res, node->left, level+1);
helper(res, node->right, level+1);
}
vector<vector<int>> levelOrderBottom(TreeNode* root) {
vector<vector<int> > res;
if(!root) return res;
helper(res, root, 0);
// 对数组进行反转
reverse(res.begin(), res.end());
return res;
}
};
Python
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def helper(self, res: List[List[int]], node: TreeNode, level: int)-> None:
if not node:
return
if len(res) == level:
res.append([])
res[level].append(node.val)
self.helper(res, node.left, level+1)
self.helper(res, node.right, level+1)
def levelOrderBottom(self, root: Optional[TreeNode]) -> List[List[int]]:
res = []
if not root:
return res
self.helper(res, root, 0)
return res[::-1]