Python easy recursive search


  • 0
    class Solution(object):
        def pathSum(self, root, sum):
            """
            :type root: TreeNode
            :type sum: int
            :rtype: List[List[int]]
            """
            if root is None:
                return []
            temp = []
            r = []
            self.search(root, 0, sum, temp, r)
            return r
            
        def search(self, root, sum, target, temp, r):
            if root.left == root.right == None and sum + root.val == target:
                t = temp[:]
                t.append(root.val)
                r.append(t)
            elif root.left is not None and root.right is not None:
                temp_l = temp[:]
                temp_r = temp[:]
                temp_l.append(root.val)
                temp_r.append(root.val)
                self.search(root.left, sum + root.val, target, temp_l, r)
                self.search(root.right, sum + root.val, target, temp_r, r)
            elif root.left is not None:
                temp_l = temp[:]
                temp_l.append(root.val)
                self.search(root.left, sum + root.val, target, temp_l, r)
            elif root.right is not None:
                temp_r = temp[:]
                temp_r.append(root.val)
                self.search(root.right, sum + root.val, target, temp_r, r)

Log in to reply
 

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