Skip to content

Instantly share code, notes, and snippets.

@jykim16
Last active August 10, 2017 16:27
Show Gist options
  • Save jykim16/d53790081340651f3754671ca8b3206c to your computer and use it in GitHub Desktop.
Save jykim16/d53790081340651f3754671ca8b3206c to your computer and use it in GitHub Desktop.
Tree has path to target sum? You are given a binary tree whose nodes all have integer values (both positive and negative). Given some target sum (say, 14), return true if there is any path starting from the root and ending in a leaf, such that adding up all the values along the path equals the given sum. const hasPathToSum = function(node, targe…
class Tree {
constructor(name, val) {
this.value = val;
this.children = [];
this.name = name;
}
addChild(child) {
this.children.push(child)
}
}
Gram = new Tree('Gram', 10)
Mom = new Tree('Mom', 5)
Gram.addChild(Mom)
Me = new Tree('Jon', -6)
Mom.addChild(Me);
Bro = new Tree('Phil', -3);
Mom.addChild(Bro);
const hasPathToSum = function(node, targetSum) {
var sumOfTree = (node, result) => {
if(result === targetSum) {
return true;
} else {
for(var i = 0; i < node.children.length; i++) {
if(sumOfTree(node.children[i], result + node.children[i].value)){
return true
};
}
}
}
var result = sumOfTree(node, node.value);
return result ? result : false;
};
hasPathToSum(Gram, 15) // true
hasPathToSum(Gram, 21) //false
hasPathToSum(Gram, 9) //true
hasPathToSum(Gram, 12) //true
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment