Sum Root to Leaf Numbers

Problem Id: 129 Difficulty: Medium Tag: Tree Tag: Depth-first Search


The key point of this problem if to get the number of each leaves. To get it, we could add an additional variable to the DFS method to pass the previous number from the root to its parent.


# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    def sumNumbers(self, root: TreeNode) -> int:
        self._numbersum = 0
        self._helper(root, 0)
        return self._numbersum

    def _helper(self, node, previous):
        if node is None:
        value = previous * 10 + node.val
        if node.left == node.right == None:
            self._numbersum += value
        self._helper(node.left, value)
        self._helper(node.right, value)