BFS

LeetCode 107 Binary Tree Level Order Traversal II (Python)

Posted by 小明MaxMing on July 2, 2020

题目

Given a binary tree, return the bottom-up level order traversal of its nodes’ values. (ie, from left to right, level by level from leaf to root).

解题思路

从根节点开始dfs,把每一层放到结果里,同时求出下一层的所有节点

代码

class Solution:
    def levelOrderBottom(self, root: TreeNode) -> List[List[int]]:
        if not root:
            return None
        res, q = [], [root]
        while q:
            val, tmp = [], []
            for node in q:
                val.append(node.val)
                if node.left:
                    tmp.append(node.left)
                if node.right:
                    tmp.append(node.right)
            res.append(val)
            q = tmp
        return res[::-1]

视频讲解 YouTube<--欢迎点击订阅

视频讲解 bilibili<--欢迎点击订阅