leetcode 480 二叉树的所有路径 (第一遍刷题)

给一棵二叉树,找出从根节点到叶子节点的所有路径。

# Definition for a binary tree node.
class TreeNode(object):
    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]
        """
        def search(root, path, res):
            """
            :path: str
            :res: List[str]
            """
            if root.left == root.right == None:#若该节点已经是叶节点
                res.append(path + str(root.val))
                # print(res)
                return res
            if root.left:
                search(root.left, path + str(root.val) + "->", res)

            if root.right:
                search(root.right, path + str(root.val) + "->", res)

        if root == None:
            return []

        output = []
        output = search(root, "", output)
        return output

root = TreeNode(3)
n1 = TreeNode(2)
root.left = n1
n2 = TreeNode(4)
root.right = n2
n1.left = TreeNode(0)
n1.right = TreeNode(8)

s = Solution()
result =s.binaryTreePaths(root)
print(result)

猜你喜欢

转载自blog.csdn.net/u013075024/article/details/90755102