Skip to content

Instantly share code, notes, and snippets.

@junjunparkpark
Created June 22, 2017 16:30
Show Gist options
  • Save junjunparkpark/a4e9da1a26d954cb14cb65a20c9cd0e3 to your computer and use it in GitHub Desktop.
Save junjunparkpark/a4e9da1a26d954cb14cb65a20c9cd0e3 to your computer and use it in GitHub Desktop.
Path to Target Sum - Interview Prompt HRSF78
/*
** 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