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).
1public class TreeNode {
2 public int val;
3 public TreeNode left;
4 public TreeNode right;
5 public TreeNode(int val=0, TreeNode left=null, TreeNode right=null) {
6 this.val = val;
7 this.left = left;
8 this.right = right;
9 }
10}
11
12public class Solution {
13 public int SumRootToLeaf(TreeNode root) {
14 return CalculateSum(root, 0);
15 }
16
17 private int CalculateSum(TreeNode node, int currentSum) {
18 if (node == null) return 0;
19 currentSum = (currentSum << 1) | node.val;
20 if (node.left == null && node.right == null) return currentSum;
21 return CalculateSum(node.left, currentSum) + CalculateSum(node.right, currentSum);
22 }
23}
The C# solution makes use of a helper function `CalculateSum` to recurse through the tree. This function accumulates bit-shifted values along paths to leaf nodes, which are then summed for 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.