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)
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容