Leetcode: Binary Tree Paths

来源:互联网 发布:手机淘宝双色球在哪里 编辑:程序博客网 时间:2024/04/28 14:45

Question

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

For example, given the following binary tree:

1
/ \
2 3
\
5
All root-to-leaf paths are:

[“1->2->5”, “1->3”]
Credits:
Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases.

Show Tags
Show Similar Problems


Analysis

pass at the first time


Solution

# Definition for a binary tree node.# class TreeNode(object):#     def __init__(self, x):#         self.val = x#         self.left = None#         self.right = Noneclass Solution(object):    def binaryTreePaths(self, root):        """        :type root: TreeNode        :rtype: List[str]        """        total = []        if root==None:            return total        return self.helper(root, [root.val], total)    def helper(self, root, cur, total):        if root.left==None and root.right==None:            temp = self.transfer(cur)            total.append(temp)            return total        if root.left!=None:            total = self.helper(root.left, cur+[root.left.val], total)        if root.right!=None:            total =self.helper(root.right, cur+[root.right.val], total)        return total    def transfer(self, lst):        if lst==[]:            return []        temp = ""        for ind, elem in enumerate(lst):            temp += str(elem)            if ind != (len(lst)-1):                temp += '->'        return temp
0 0