• Leetcode 257. Binary Tree Paths


    Description: Given the root of a binary tree, return all root-to-leaf paths in any order.

    A leaf is a node with no children.

    Link: 257. Binary Tree Paths

    Examples:

    Example 1:
    
    Input: root = [1,2,3,null,5]
    Output: ["1->2->5","1->3"]
    
    Example 2:
    Input: root = [1]
    Output: ["1"]

    思路: 返回所有从root到叶子节点的路径,又是返回所有解,回溯法。

    class Solution(object):
        def binaryTreePaths(self, root):
            """
            :type root: TreeNode
            :rtype: List[str]
            """
            self.res = []
            self.dfs(root, '')
            return self.res
        
        def dfs(self, root, path):
            if not root.left and not root.right:
                path += '->'+str(root.val)
                self.res.append(path[2:])
                return
            if root.left:
                self.dfs(root.left, path+'->'+str(root.val))
            if root.right:
                self.dfs(root.right, path+'->'+str(root.val))

    日期: 2021-04-19

  • 相关阅读:
    JDBC
    SQL语法(3)
    数据库设计和三大范式
    SQL语法(2)
    SQL语法(1)
    数据库的概念以及MYSQL的安装和卸载
    IO流(下)
    IO流(上)
    bash: javac: command not found...
    R语言绘制地图
  • 原文地址:https://www.cnblogs.com/wangyuxia/p/14678410.html
Copyright © 2020-2023  润新知