404. Sum of Left Leaves #146
-
Topics: Given the A leaf is a node with no children. A left leaf is a leaf that is the left child of another node. Example 1:
Example 2:
Constraints:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
We can implement a solution using recursion. Given the constraints and requirements, we will define a function to sum the values of all left leaves in a binary tree.
Let's implement this solution in PHP: 404. Sum of Left Leaves <?php
// Definition for a binary tree node.
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;
}
}
// Define a tree node as an associative array for simplicity
// ['val' => value, 'left' => left_child, 'right' => right_child]
// Function to compute the sum of left leaves
function sumOfLeftLeaves($root) {
if ($root === null) {
return 0;
}
$sum = 0;
// Check if the left child is a leaf node
if (isset($root['left'])) {
if ($root['left']['left'] === null && $root['left']['right'] === null) {
$sum += $root['left']['val'];
} else {
$sum += sumOfLeftLeaves($root['left']);
}
}
// Recur for the right child
$sum += sumOfLeftLeaves($root['right']);
return $sum;
}
// Example usage:
// Create the binary tree [3,9,20,null,null,15,7]
$root = new TreeNode(3);
$root->left = new TreeNode(9);
$root->right = new TreeNode(20);
$root->right->left = new TreeNode(15);
$root->right->right = new TreeNode(7);
echo sumOfLeftLeaves($root); // Output: 24
// For a single node tree [1]
$root2 = new TreeNode(1);
echo sumOfLeftLeaves($root2); // Output: 0
?> Explanation:
Complexity:
|
Beta Was this translation helpful? Give feedback.
We can implement a solution using recursion. Given the constraints and requirements, we will define a function to sum the values of all left leaves in a binary tree.
Define the Binary Tree Node Structure: Since PHP 5.6 doesn’t support classes with properties as easily, we use arrays to represent the tree nodes.
Recursive Function: Implement a recursive function to traverse the tree and sum the values of left leaves.
Let's implement this solution in PHP: 404. Sum of Left Leaves