zoukankan      html  css  js  c++  java
  • 257.Binary Tree Paths(打印二叉树所有路径,递归)

    Given a binary tree, return all root-to-leaf paths.

    Note: A leaf is a node with no children.

    Example:

    Input:

       1
     /   
    2     3
     
      5
    

    Output: ["1->2->5", "1->3"]

    Explanation: All root-to-leaf paths are: 1->2->5, 1->3

    # Definition for a binary tree node.
    class TreeNode:
        def __init__(self, x):
            self.val = x
            self.left = None
            self.right = None
    
    class Solution:
        def binaryTreePaths(self, root):
            """
            :type root: TreeNode
            :rtype: List[str]
            """
            res = []
            def dfs(root,s):
                if root.left is None and root.right is None:
                    res.append(s)
                if root.left:
                    dfs(root.left,s + '->' + str(root.left.val))
                if root.right:
                    dfs(root.right,s + '->' + str(root.right.val))
            if root is None:
                return res
            dfs(root,str(root.val))
            return res
    
    root = TreeNode(1)
    root.left = TreeNode(2)
    root.right = TreeNode(3)
    root.left.right = TreeNode(4)
    print(Solution.binaryTreePaths(0,root))
    
  • 相关阅读:
    51Nod1528 加号分配
    51Nod1679 连通率
    51Nod1679 连通率
    51Nod1426 沙拉酱括号
    51Nod1426 沙拉酱括号
    51Nod1678 lky与gcd
    51Nod1556 计算
    c学习第2天
    Stopwatch秒表的使用
    数据从.txt文件中导入数据库
  • 原文地址:https://www.cnblogs.com/bernieloveslife/p/9747737.html
Copyright © 2011-2022 走看看