美文网首页
Contest 131 - Prob 2 Sum of Root

Contest 131 - Prob 2 Sum of Root

作者: 人树杨 | 来源:发表于2019-04-07 12:05 被阅读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 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)
    

    相关文章

      网友评论

          本文标题:Contest 131 - Prob 2 Sum of Root

          本文链接:https://www.haomeiwen.com/subject/cizjiqtx.html