• 257. 二叉树的所有路径




    代码一

    class Solution(object):
        # 思路:用前序式DFS,从root到叶子。
        def binaryTreePaths(self, root):
            """
            :type root: TreeNode
            :rtype: List[str]
            """
            if not root:
                return []
            res = []
            return self.pre_DFS(root, res, "")
    
        def pre_DFS(self, root, res, road):
            if root:
                road += str(root.val)
                if not root.left and not root.right:
                    res.append(road)
                else:
                    road += '->'
                    self.pre_DFS(root.left, res, road)
                    self.pre_DFS(root.right, res, road)
            return res
    

    代码二

    class Solution(object):
        def binaryTreePaths(self, root):
            """
            :type root: TreeNode
            :rtype: List[str]
            """
            if not root:
                return []
            if not root.left and not root.right:
                return [str(root.val)]
            pathList = []
            if root.left:
                pathList += self.binaryTreePaths(root.left)
            if root.right:
                pathList += self.binaryTreePaths(root.right)
            for index, path in enumerate(pathList):
                pathList[index] = str(root.val) + "->" + path
            return pathList
    

    用list返回二叉树的所有路径。

    class Solution(object):
        # 前序式DFS——用list返回二叉树的所有路径
        # 注意每趟递归前要将当前节点pop()掉
        def pre_DFS(self, node, res, road):
            # 当前节点为空,直接return
            if not node:
                return
            # 否则将当前节点加入路径中
            road.append(node.val)
            # 当前节点是叶子则将路径加入外层list中
            if not node.left and not node.right:
                res.append(list(road))
            # 前序式递归当前节点的左右子树
            self.pre_DFS(node.left, res, road)
            self.pre_DFS(node.right, res, road)
            # 每趟递归前将当前节点pop()
            road.pop()
            # 返回外层list
            return res
    
  • 相关阅读:
    如何统计一个字符串中某个字符出现的次数
    从GitHub克隆项目到本地
    nginx能做什么
    dubbo的使用实例
    zookeeper单机安装
    Http发送post(x-www-form-urlencoded)请求
    集群与分布式的区别
    cas的客户端应用是负载均衡,单点退出怎么办?
    mybatis执行DDL语句
    sql server 行列互换
  • 原文地址:https://www.cnblogs.com/panweiwei/p/13754755.html
Copyright © 2020-2023  润新知