Sum of Root to Leaf Binary Numbers LeetCode Solution

Day 10/30 – LeetCode streak Today’s problem: Sum of Root To Leaf Binary Numbers. Each root-to-leaf path in the tree forms a binary number (top is MSB, leaf is LSB), and you need the sum of all such numbers. The pattern is a clean DFS with a running value: -As you go down the tree, carry a 'current' integer that represents the binary number so far. -At each node, shift left and add the node’s bit: 'current = (current << 1) | node.val. -When you hit a leaf ('left == null' and 'right == null'), return 'current' because that path is now a complete binary number. -For internal nodes, return 'dfs(left, current) + dfs(right, current)' so the sums bubble up. Day 10 takeaway: This is a nice example of “carry state down the recursion instead of storing the whole path” — the bit shift builds the number on the fly, and the recursion naturally adds up all path values. #leetcode #dsa #java #binarytree #consistency

  • graphical user interface

Appreciate your consistency brother keep going

To view or add a comment, sign in

Explore content categories