Sum of Root To Leaf Binary Numbers
You need to compute the sum of the binary numbers represented by each root-to-leaf path in a binary tree, where each node has a value of 0 or 1.
Here’s an approach to solve this problem:
- Use Depth-First Search (DFS) to traverse the tree.
- Maintain a current number, representing the binary number constructed from the root to the current node.
- When reaching a leaf node, add the current number to the sum.
- Return the total sum.
|
|
Explanation:
- The function
dfs
recursively traverses the tree. - In each call, it updates
current_number
by left-shifting its binary representation and adding the current node’s value (this corresponds to adding a new bit to the binary number). - If the current node is a leaf, the function returns the current number.
- If the current node has children, the function calls itself recursively on the left and right children, and returns the sum of the results.
- Finally, the main function calls
dfs
starting from the root, with an initial current number of 0, and returns the result.