DEV Community

Miss Pooja Anilkumar Patel
Miss Pooja Anilkumar Patel

Posted on

1

129. Leetcode Solution in Javascript

/**
 * Definition for a binary tree node.
 * function TreeNode(val, left, right) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.left = (left===undefined ? null : left)
 *     this.right = (right===undefined ? null : right)
 * }
 */
/**
 * @param {TreeNode} root
 * @return {number}
 */
var sumNumbers = function(root) {
    if (!root) return 0;
    var total = [];
    helper(root, 0, total);
    var sum = 0;
    for (var i = 0; i < total.length; i++) {
        sum += total[i];
    }
    return sum;
};

var helper = function(root, sum, total) {
    sum = 10 * sum + root.val;
    if (root.left === null && root.right === null) {
        total.push(sum);
        return;
    }
    if (root.left) {
        helper(root.left, sum, total);
    }
    if (root.right) {
        helper(root.right, sum, total);
    }
};

// a better and more concise solution
var sumNumbers = function(root) {
    return helper(root, 0);
};

var helper = function(root, sum) {
    if (!root)  return 0;
    if (root.left === null && root.right === null) {
        return 10 * sum + root.val;
    }
    return  helper(root.left, 10 * sum + root.val)
            + helper(root.right, 10 * sum + root.val);
};

// a third DFS method. Top-down
var sumNumbers = function(root) {
    if (!root) return 0;
    return helper(root, 0, 0);
};

function helper(root, currNum, sum) {
    if (!root) return sum;
    currNum = root.val + 10 * currNum;
    if (!root.left && !root.right) {
        sum += currNum;
        return sum;
    }
    return helper(root.left, currNum, sum) + helper(root.right, currNum, sum)
}
Enter fullscreen mode Exit fullscreen mode

leetcode

solution

Here is the link for the problem:
https://leetcode.com/problems/sum-root-to-leaf-numbers/

Sentry blog image

How I fixed 20 seconds of lag for every user in just 20 minutes.

Our AI agent was running 10-20 seconds slower than it should, impacting both our own developers and our early adopters. See how I used Sentry Profiling to fix it in record time.

Read more

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay