Friedrich Ewald My Personal Website

Leetcode: Sum Root to Leaf Numbers

Multiple things to note:

  • Make sure to visit only left and right if they exist respectively
  • Sum up as str, then finally convert to integer
  • Consider nodes which have only a left or only a right child node, they’re not leaf nodes.
# 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.inner(root, '')
  
  def inner(self, root: Optional[TreeNode], path: str) -> int:
    v = str(root.val)
    if root.left is None and root.right is None:
      return int(path + v)
    
    s = 0
    if root.left is not None:
      s += self.inner(root.left, path + v)
    if root.right is not None:
      s += self.inner(root.right, path + v)
    return s

About the author

is a Staff Software Engineer with a Master's degree in Computer Science. He started this website in late 2015, mostly as a digital business card. He is interested in Go, Python, Ruby, SQL- and NoSQL-databases, machine learning and AI and is experienced in building scalable, distributed systems and micro-services at multiple larger and smaller companies.