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))
原文地址:https://www.cnblogs.com/bernieloveslife/p/9747737.html