Leetcode 1079 Solution

This article provides solution to leetcode question 1079 (sum-of-root-to-leaf-binary-numbers)

https://leetcode.com/problems/sum-of-root-to-leaf-binary-numbers

Solution

# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None
class Solution: def sumRootToLeaf(self, root: TreeNode) -> int: self.ans = 0
def dfs(node, val): val = 2 * val + node.val
if not node.left and not node.right: self.ans += val else: if node.left: dfs(node.left, val) if node.right: dfs(node.right, val)
dfs(root, 0) return self.ans