129. Sum Root to Leaf Numbers #101
-
Topics: You are given the root of a binary tree containing digits from Each root-to-leaf path in the tree represents a number.
Return the total sum of all root-to-leaf numbers. Test cases are generated so that the answer will fit in a 32-bit integer. A leaf node is a node with no children. Example 1:
Example 2:
Constraints:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
We can use a Depth-First Search (DFS) approach. The idea is to traverse the tree, keeping track of the number formed by the path from the root to the current node. When you reach a leaf node, you add the current number to the total sum. Let's implement this solution in PHP: 129. Sum Root to Leaf Numbers <?php
class TreeNode {
public $val = null;
public $left = null;
public $right = null;
public function __construct($val = 0, $left = null, $right = null) {
$this->val = $val;
$this->left = $left;
$this->right = $right;
}
}
function sumNumbers($root) {
return sumNumbersRecu($root, 0);
}
function sumNumbersRecu($node, $currentSum) {
if ($node === null) {
return 0;
}
// Update the current sum with the value of the current node
$currentSum = $currentSum * 10 + $node->val;
// If the node is a leaf, return the current sum
if ($node->left === null && $node->right === null) {
return $currentSum;
}
// Recursively call dfs for left and right children
return sumNumbersRecu($node->left, $currentSum) + sumNumbersRecu($node->right, $currentSum);
}
// Example usage:
// Example 1
$root1 = new TreeNode(1);
$root1->left = new TreeNode(2);
$root1->right = new TreeNode(3);
echo sumNumbers($root1); // Output: 25
// Example 2
$root2 = new TreeNode(4);
$root2->left = new TreeNode(9);
$root2->right = new TreeNode(0);
$root2->left->left = new TreeNode(5);
$root2->left->right = new TreeNode(1);
echo sumNumbers($root2); // Output: 1026
?> Explanation:
Edge Cases:
This solution runs efficiently with a time complexity of O(n), where n is the number of nodes in the tree. This is because each node is visited exactly once. The space complexity is O(h), where h is the height of the tree, due to the recursion stack. |
Beta Was this translation helpful? Give feedback.
We can use a Depth-First Search (DFS) approach. The idea is to traverse the tree, keeping track of the number formed by the path from the root to the current node. When you reach a leaf node, you add the current number to the total sum.
Let's implement this solution in PHP: 129. Sum Root to Leaf Numbers