#1022

Sum of Root To Leaf Binary Numbers

Easy
TreeDepth-First SearchBinary TreeDepth-First SearchBinary Tree Traversal
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(h)
💡

Intuition

Time O(n)Space O(h)

We can use a depth-first search (DFS) approach while maintaining the current binary number as we traverse the tree. This avoids the need for multiple traversals and directly computes the sum.

⚙️

Algorithm

3 steps
  1. 1Step 1: Use DFS to traverse the tree, passing the current binary number formed by the path.
  2. 2Step 2: For each node, update the current number by shifting left and adding the node's value.
  3. 3Step 3: When a leaf node is reached, add the current number to the total sum.
solution.py18 lines
1# Full working Python code
2class TreeNode:
3    def __init__(self, val=0, left=None, right=None):
4        self.val = val
5        self.left = left
6        self.right = right
7
8class Solution:
9    def sumNumbers(self, root: TreeNode) -> int:
10        def dfs(node, current_number):
11            if not node:
12                return 0
13            current_number = (current_number << 1) | node.val
14            if not node.left and not node.right:
15                return current_number
16            return dfs(node.left, current_number) + dfs(node.right, current_number)
17
18        return dfs(root, 0)

Complexity note: The time complexity is O(n) because we visit each node exactly once. The space complexity is O(h) due to the recursion stack, where h is the height of the tree.

  • 1Binary numbers can be efficiently calculated using bit manipulation.
  • 2Depth-first search is a natural fit for tree traversal problems.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.