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))
    
  • 相关阅读:
    使用基本的socket函数
    ODBC、ADO
    MFC开发ActiveX控件的简介
    MFC线程
    系统API函数实现多线程及线程同步
    IP地址控件
    加速键
    属性页对话框
    Tab控件
    树控件
  • 原文地址:https://www.cnblogs.com/bernieloveslife/p/9747737.html
Copyright © 2011-2022 走看看