Algorithm

Sum of Root To Leaf Binary Numbers

Solution
class Solution:
    def sumRootToLeaf(self, root: Optional[TreeNode]) -> int:
        def dfs(node, current_val):
            if not node:
                return 0
            
            # Shift left by 1 and add the current node's bit
            current_val = (current_val << 1) | node.val
            
            # If it's a leaf, return the calculated value
            if not node.left and not node.right:
                return current_val
            
            # Otherwise, keep going down both sides
            return dfs(node.left, current_val) + dfs(node.right, current_val)
        
        return dfs(root, 0)

Time Complexity

Unknown

Space Complexity

Unknown