Leetcode: Sum Root to Leaf Numbers
Multiple things to note:
- Make sure to visit only
left
andright
if they exist respectively - Sum up as
str
, then finally convert to integer - Consider nodes which have only a
left
or only aright
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