美文网首页
【BFS+DFS】107 -- 层序遍历II

【BFS+DFS】107 -- 层序遍历II

作者: 何几时 | 来源:发表于2021-07-10 17:24 被阅读0次
    # 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 levelOrderBottom(self, root: TreeNode) -> List[List[int]]:
            retList = []
            level = 0
            self.dfs(root, retList, level)
            retList = self.reverseListTwoPoiters(retList)
    
            return retList
    
        def dfs(self, root, retList, level):
            # 实际操作
            ## 如果 retList 的长度不足时,要 append 一个空列表
            if len(retList) < level + 1:
                retList.append([])
            ## 添加进 retList
            retList[level].append(root.val)
    
            # 终止条件
            if root.left is None and root.right is None:
                return
    
            # 递归拆解
            if root.left is not None:
                self.dfs(root.left, retList, level + 1)
            
            if root.right is not None:
                self.dfs(root.right, retList, level + 1)
        
        def reverseListTwoPoiters(self, retList):
            if len(retList) == 0:
                return retList
            left = 0
            right = len(retList) - 1
    
            while left < right:
                tmp = retList[left]
                retList[left] = retList[right]
                retList[right] = tmp
    
                left += 1
                right -= 1
    
            return retList
    
        def reverseListByRecursion(self, retList):
            return retList
    

    运行以上命令会出现以下错误


    输入是: []
    错误原因:没有在程序一开始就加上 corner case
    修改位置:
    class Solution:
        def levelOrderBottom(self, root: TreeNode) -> List[List[int]]:
            if root is None:
                return []
            retList = []
            # ...
    

    相关文章

      网友评论

          本文标题:【BFS+DFS】107 -- 层序遍历II

          本文链接:https://www.haomeiwen.com/subject/zkgcpltx.html