Simple to understand Python solution


  • 3
    A
    class Solution(object):
        def binaryTreePaths(self, root):
            if root == None:
                return []
            return self.constructPaths(root, str(root.val), [])
    
        def constructPaths(self, root, p, paths):
            if root.left == None and root.right == None:
                paths.append(p)
            if root.left:
                paths = self.constructPaths(root.left, p + "->" + str(root.left.val), paths)
            if root.right:
                paths = self.constructPaths(root.right, p + "->" + str(root.right.val), paths)
            return paths

  • 1
    D

    is your solution pass the test ? how do you merge left path and right path?
    below is my solution :

    class Solution(object):
        def binaryTreePaths(self, root):
            self.allPaths = []
            if not root:
                return []
            paths = str(root.val)
            if not root.left and not root.right:
                return [paths]
            
            if  root.left:
                self.defs(root.left, paths)
            if root.right:
                self.defs(root.right, paths)
            return self.allPaths
        def defs(self, root, paths):
            paths += "->"
            paths += str(root.val)
            if not root.left and not root.right:
                self.allPaths.append(paths)
            if root.left:
                self.defs(root.left, paths)
            if root.right:
                self.defs(root.right, paths)

  • 0
    A

    Yes it did pass the test. You merge the left paths and right paths by recursing on the left subtree first and passing the returned path list to right subtree.


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.