Problem statement

https://binarysearch.com/problems/Sum-of-Digit-Paths-in-a-Tree/

Solution

Equal to Leetcode 0129. Sum Root to Leaf Numbers.

Complexity

Time is O(n), space is O(h).

Code

class Solution:
    def solve(self, root):
        if not root: return 0
        if not root.left and not root.right:
            return int(root.val)
        
        if root.left: root.left.val = 10*root.val + root.left.val
        if root.right: root.right.val = 10*root.val + root.right.val
            
        return self.solve(root.left) + self.solve(root.right)