class Solution:
def sumRootToLeaf(self, root: Optional[TreeNode]) -> int:
# DFS with stack storing (node, prefix)
# For each node, mark node as visited, visit left, then right child
# When a leaf is reached, add leaf binary number to result
stack = [(root, str(root.val))]
result = 0
while stack:
node, prefix = stack.pop()
has_left = False
has_right = False
if not hasattr(node, 'visited'):
node.visited = True
if hasattr(node, 'left') and node.left:
stack.append((node.left, prefix + str(node.left.val)))
has_left = True
if hasattr(node, 'right') and node.right:
stack.append((node.right, prefix + str(node.right.val)))
has_right = True
if not (has_left or has_right): # Leaf node
result += int(prefix, 2)
return result