美文网首页leetcode和算法----日更
leetcode 275 二叉树所有的路径

leetcode 275 二叉树所有的路径

作者: Arsenal4ever | 来源:发表于2020-01-26 22:49 被阅读0次

我觉得我手生了。先开全局变量,然后递归找叶子节点,维护路径,如果是叶子节点就把路径添加到全局变量中。

# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution(object):
    def binaryTreePaths(self, root):
        """
        :type root: TreeNode
        :rtype: List[str]
        """
        if not root:
            return []
        self.result = []
        self.binaryPath(root, "")
        return self.result

    def binaryPath(self, root, path):
        if not root.left and not root.right:
            path += str(root.val)
            self.result.append(path)
        if root.left:
            path1 = path + str(root.val) + str("->")
            self.binaryPath(root.left, path1)
        if root.right:
            path2 = path + str(root.val) + str("->")
            self.binaryPath(root.right, path2)

相关文章

网友评论

    本文标题:leetcode 275 二叉树所有的路径

    本文链接:https://www.haomeiwen.com/subject/cyjsthtx.html