DEV Community

Ashutosh Sarangi
Ashutosh Sarangi

Posted on

1 1 1 1 1

Algo:: Tree Sum Should Match the Target

LeetCode 112. Path Sum easy problem .

Question

  • Given the root of a binary tree and an integer targetSum, return true if the tree has a root-to-leaf path such that adding up all the values along the path equals targetSum.
  • A leaf is a node with no children.

Solution

var hasPathSum = function(root, targetSum) {

    let sum = 0;

    const helper = (root) => {
        if (root === null) {
            return;
        }

        sum += root.val;

        if (sum === targetSum && (root.left == null && root.right === null)) {
            return true;
        }

        if (helper(root.left)){
            return true;
        }
        if (helper(root.right)) {
            return true;
        };
        sum -= root.val;
    }

    return helper(root) ? true : false;
};
Enter fullscreen mode Exit fullscreen mode

If it is not clear please check my other Article on Tree Algorithm then it will be very much easier to understand.

Feel Free to reach out to me if you have any concerns.

Reference:-

  1. https://leetcode.com/problems/path-sum/?envType=study-plan-v2&envId=top-interview-150

Heroku

Build apps, not infrastructure.

Dealing with servers, hardware, and infrastructure can take up your valuable time. Discover the benefits of Heroku, the PaaS of choice for developers since 2007.

Visit Site

Top comments (0)

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

👋 Kindness is contagious

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

Okay