Created
March 27, 2022 10:55
-
-
Save esase/bf5facac1eb0f8592d722c178819d586 to your computer and use it in GitHub Desktop.
Path sum [https://leetcode.com/problems/path-sum]
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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