Created
June 22, 2017 16:30
-
-
Save junjunparkpark/a4e9da1a26d954cb14cb65a20c9cd0e3 to your computer and use it in GitHub Desktop.
Path to Target Sum - Interview Prompt HRSF78
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
/* | |
** Assuming that the tree is instantiated with the following: ** | |
class Tree { | |
constructor(value) { | |
this.value = value; | |
this.children = []; | |
} | |
addChild(value) { | |
let child = new Tree(value) | |
this.children.push(child); | |
return child; | |
} | |
} | |
*/ | |
const hasPathToSum = function(node, targetSum) { | |
let result = false; | |
const getBranchSums = function(currentNode, currentSum) { | |
if (currentSum === targetSum) { result = true; } | |
if (currentNode.children.length > 0) { currentNode.children.forEach(child => getBranchSums(child, currentSum + child.value)); } | |
} | |
getBranchSums(node, node.value) | |
return result; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment