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).
1class TreeNode:
2 def __init__(self, val=0, left=None, right=None):
3 self.val = val
4 self.left = left
5 self.right = right
6
7class Solution:
8 def sumRootToLeaf(self, root: TreeNode) -> int:
9 return self.calculateSum(root, 0)
10
11 def calculateSum(self, node: TreeNode, currentSum: int) -> int:
12 if not node:
13 return 0
14 currentSum = (currentSum << 1) | node.val
15 if not node.left and not node.right:
16 return currentSum
17 return self.calculateSum(node.left, currentSum) + self.calculateSum(node.right, currentSum)
This Python implementation involves recursively traversing a binary tree and computing binary sums as decimal for each root-to-leaf path. We accumulate these sums to achieve the final result.
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.
1class TreeNode:
2
This Python implementation leverages a stack to perform iterative DFS. A tuple tracks each node alongside the current binary sum being accumulated. The process ensures all leaf nodes' paths are accounted for, computing a total sum iteratively.