Simple Python solution [82ms]


  • 1
    S
    class Solution:
    # @param root, a tree node
    # @param sum, an integer
    # @return a list of lists of integers
    def pathSum(self, root, sum):
    	paths = []
    	if root is not None:
        	if root.val == sum and not root.left and not root.right:
        		paths.append([root.val])
        	else:
        		sum -= root.val
        		leftPaths = self.pathSum(root.left, sum)
        		if len(leftPaths) > 0:
        			for path in leftPaths:
        				path.insert(0, root.val)
        				paths.append(path)
        			
        		rightPaths = self.pathSum(root.right, sum)
        		if len(rightPaths) > 0:
        			for path in rightPaths:
        				path.insert(0, root.val)
        				paths.append(path)
    	return paths

Log in to reply
 

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