二叉树-层序遍历 leetcode 107

41 阅读1分钟

感谢代码随想录

  1. 从根节点开始。记录当前层的节点。
  2. 遍历当前层节点的同时。记录当前层节点的值,和下一层的节点。
  3. 重复第2步,直到当前层节点为空

leetcode 107题解 107. 二叉树的层序遍历 II - 力扣(LeetCode)

class Solution:
    def levelOrderBottom(self, root: Optional[TreeNode]) -> List[List[int]]:
        # 初始化
        # 节点为空,直接返回空列表
        # 节点不为空,初始化当前层节点列表
        # 初始化总结果列表
        if not root: return []
        nodelist = [root]
        ans = []

        # 当节点列表不为空时
        # 遍历每层的节点列表,用列表记录当前层节点的值,并且获取下一层的节点记录在下一层的节点列表中。
        # 当前层节点值列表添加到总结果中。
        while nodelist:
            curans = []
            nextnodelist = []
            for node in nodelist:
                curans.append(node.val)
                if node.left: nextnodelist.append(node.left)
                if node.right: nextnodelist.append(node.right)
            nodelist = nextnodelist  
            ans.append(curans)

        # 返回总结果的反序
        return ans[::-1]