Contest 131 - Prob 2 Sum of Root
2019-04-07 本文已影响0人
人树杨
- DFS can solve the problem.
- Use a variable
total
to represent the binary number corresponding to the path from the root to the parent of thisnode
. When visit the children of thisnode
, the number becomestotal = total * 2 + node.val
. - If this
node
does not have any children, then it is the time to add the numbertotal
to the resultself.sum
.
class Solution:
def sumRootToLeaf(self, root: TreeNode) -> int:
def dfs(node, total):
if not node: return
total = total * 2 + node.val
if not node.left and not node.right: self.sum += total
dfs(node.left, total)
dfs(node.right, total)
self.sum = 0
dfs(root, 0)
return self.sum % (10**9 + 7)