LeetCode PathSum
112 Path Sum 和113 Path Sum2 关注的是从root到leaf的情况,437 Path Sum3 关注的是任一点 downwards到某一个点的情况。 三题感觉都是比较典型的dfs题。
112 # Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def hasPathSum(self, root: TreeNode, s: int) -> bool: if not root: return False if root and not root.right and not root.left: return root.val == s return self.hasPathSum(root.left, s-root.val) or self.hasPathSum(root.right, s-root.val)
113 # Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def pathSum(self, root: TreeNode, s: int) -> List[List[int]]: if not root: return [] self.res = [] self.dfs(root, s, [], 0) return self.res def dfs(self, root, s, path, cur): if not root: return if cur + root.val== s and not root.left and not root.right: path+=[root.val] self.res.append(path) return self.dfs(root.left, s, path+[root.val], cur+root.val) self.dfs(root.right, s, path+[root.val], cur+root.val)
437 # Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def pathSum(self, root: TreeNode, s: int) -> int: if not root: return 0 return (self.dfs(root, s, 0, [0])[0]//2 + self.pathSum(root.left, s) + self.pathSum(root.right, s)) def dfs(self, root, s, cur, count): if cur == s: count[0] += 1 if not root: return count self.dfs(root.left, s, cur+root.val, count) self.dfs(root.right, s, cur+root.val, count) return count
浙公网安备 33010602011771号