Sum root to leaf

problem

Same as the last problem. We only want to add when there's no left or right node. State is kept by function.

from typing import Optional
# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def sumNumbers(self, root: Optional[TreeNode]) -> int:
        return self.dfs(root, 0)
    
    def dfs(self, node, currSum) -> int:

        if node == None:
            return 0
        
        if node.left == None and node.right == None:
            return int(str(currSum) + str(node.val))
        
        else:
            currSum = str(currSum) + str(node.val)
            return self.dfs(node.left, currSum) + self.dfs(node.right, currSum)