zoukankan      html  css  js  c++  java
  • 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
    
  • 相关阅读:
    在python中使用正则表达式(二)
    在python中使用正则表达式(一)
    利用cookies进行登录并封装请求方法
    fiddler学习笔记&&基本使用
    理解css相邻兄弟选择器
    selenium+Page Objects(第三话)
    selenium+Page Objects(第二话)
    selenium+Page Objects(第一话)
    python+selenium基础之XPATH轴定位(第二篇)
    关于类、方法、对象(实例):静态方法
  • 原文地址:https://www.cnblogs.com/panweiwei/p/13754755.html
Copyright © 2011-2022 走看看