DEV Community

ZeeshanAli-0704
ZeeshanAli-0704

Posted on

Path Sum- Binary Tree

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.

Example 1:

Input: root = [5,4,8,11,null,13,4,7,2,null,null,null,1], targetSum = 22
Output: true
Explanation: The root-to-leaf path with the target sum is 22.

/**
 * 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
 * @param {number} targetSum
 * @return {boolean}
 */
var hasPathSum = function(root, targetSum) {
    if (root === null) {
    return false;
  }
  const currentSum = 0;
  return checkSum(root, targetSum, currentSum);
};

const checkSum = (root, targetSum, currentSum) => {
  if (root === null) {
    return false;
  }
  currentSum = currentSum + root.val;
  if (root.left === null && root.right === null) {
    return currentSum === targetSum;
  }

  if (root.left) {
    let bool = checkSum(root.left, targetSum, currentSum);
    if (bool) {
      return bool;
    }
  }
  if (root.right) {
    let bool = checkSum(root.right, targetSum, currentSum);
    if (bool) {
      return bool;
    }
  }
    return false;
};


Enter fullscreen mode Exit fullscreen mode

Tiugo image

Modular, Fast, and Built for Developers

CKEditor 5 gives you full control over your editing experience. A modular architecture means you get high performance, fewer re-renders and a setup that scales with your needs.

Start now

Top comments (0)

👋 Kindness is contagious

Engage with a wealth of insights in this thoughtful article, cherished by the supportive DEV Community. Coders of every background are encouraged to bring their perspectives and bolster our collective wisdom.

A sincere “thank you” often brightens someone’s day—share yours in the comments below!

On DEV, the act of sharing knowledge eases our journey and forges stronger community ties. Found value in this? A quick thank-you to the author can make a world of difference.

Okay