Sponsored
Sponsored
This approach involves using a recursive function to traverse the binary tree from the root to the leaves. During the traversal, we calculate the binary number formed by the path from the root to the current node, then sum up the numbers obtained when a leaf node is reached. The traversal is achieved using depth-first search (DFS).
Time Complexity: O(n), where n is the number of nodes in the tree because each node is visited once.
Space Complexity: O(h), where h is the height of the tree, due to the recursion stack. In the worst case, it could be O(n).
1function TreeNode(val, left, right) {
2 this.val = (val===undefined ? 0 : val)
3 this.left = (left===undefined ? null : left)
4 this.right = (right===undefined ? null : right)
5}
6
7var sumRootToLeaf = function(root) {
8 return calculateSum(root, 0);
9};
10
11function calculateSum(node, currentSum) {
12 if (node === null) return 0;
13 currentSum = (currentSum << 1) | node.val;
14 if (node.left === null && node.right === null) return currentSum;
15 return calculateSum(node.left, currentSum) + calculateSum(node.right, currentSum);
16}
This JavaScript function uses recursion in `calculateSum` to traverse the tree in a depth-first manner, updating the sum via bit manipulation. It returns the sum from all possible root-to-leaf binary representations.
This approach utilizes an iterative technique employing a stack to carry out a DFS. In each iteration, nodes are retrieved alongside their corresponding computed binary sum. This method is advantageous when stack overflow due to recursion is a concern, as it emulates recursion iteratively.
Time Complexity: O(n), due to visiting each node once.
Space Complexity: O(n), bounded by the stack's requirement to store node-state pairs.
1import java.util.Stack;
In this Java solution, a stack is employed to simulate the recursion process iteratively. Each `Pair` in the stack holds a tree node and the current binary sum. The stack facilitates traversing the tree and computing the sum without needing traditional recursion.