Contest 131 - Prob 2 Sum of Root To Leaf Binary Numbers

  • 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 this node. When visit the children of this node, the number becomes total = total * 2 + node.val.
  • If this node does not have any children, then it is the time to add the number total to the result self.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)