Created
July 2, 2018 03:33
-
-
Save aglaiawong/b3c5934def8cf429d3f4738c69cb3164 to your computer and use it in GitHub Desktop.
PathSum_59ms
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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 pathSum(self, root, sum): | |
""" | |
:type root: TreeNode | |
:type sum: int | |
:rtype: List[List[int]] | |
""" | |
""" | |
DFS, with temp sum and target | |
check is leaf or not first before put into result | |
""" | |
result = [] | |
def walk(node, target, sum_temp, result_temp): | |
if not node: | |
return | |
sum_temp += node.val | |
result_temp.append(node.val) | |
if sum_temp == target: | |
if node.left is None and node.right is None: | |
result.append(result_temp[:]) | |
walk(node.left, target, sum_temp, result_temp) | |
walk(node.right, target, sum_temp, result_temp) | |
result_temp.pop() | |
result = [] | |
walk(root, sum, 0, []) | |
return result | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment