Skip to content

129. Sum Root to Leaf Numbers #101

Answered by topugit
mah-shamim asked this question in Q&A
Discussion options

You must be logged in to vote

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

Replies: 1 comment 2 replies

Comment options

You must be logged in to vote
2 replies
@mah-shamim
Comment options

mah-shamim Aug 15, 2024
Maintainer Author

@topugit
Comment options

topugit Aug 15, 2024
Collaborator

Answer selected by mah-shamim
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
question Further information is requested medium Difficulty
2 participants