Home > Web Front-end > JS Tutorial > Algo:: Tree Sum Should Match the Target

Algo:: Tree Sum Should Match the Target

Linda Hamilton
Release: 2024-10-05 16:22:02
Original
892 people have browsed it

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;
};


Copy after login

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

The above is the detailed content of Algo:: Tree Sum Should Match the Target. For more information, please follow other related articles on the PHP Chinese website!

source:dev.to
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template