Skip to content

Instantly share code, notes, and snippets.

@esase
Created March 27, 2022 10:55
Show Gist options
  • Save esase/bf5facac1eb0f8592d722c178819d586 to your computer and use it in GitHub Desktop.
Save esase/bf5facac1eb0f8592d722c178819d586 to your computer and use it in GitHub Desktop.
/**
* 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) {
return recursiveSearch(root, 0, targetSum) === true;
};
var recursiveSearch = function(node, currentValue, targetSum) {
if (!node) {
return false;
}
currentValue += node.val;
if (!node.left && !node.right && targetSum === currentValue) {
return true;
}
if (node.left) {
const leftResult = recursiveSearch(node.left, currentValue, targetSum);
if (leftResult) {
return true;
}
}
if (node.right) {
const rightResult = recursiveSearch(node.right, currentValue, targetSum);
if (rightResult) {
return true;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment