Skip to content

Instantly share code, notes, and snippets.

@kennyxcao
Created September 28, 2017 16:31
Show Gist options
  • Save kennyxcao/09fe543ee4d46b8d1bd86f6dcbfe9d4c to your computer and use it in GitHub Desktop.
Save kennyxcao/09fe543ee4d46b8d1bd86f6dcbfe9d4c to your computer and use it in GitHub Desktop.
var Tree = function (val) {
this.val = val;
this.children = [];
};
const hasPathToSum = function(node, targetSum) {
if (node.val === targetSum) {
return true;
}
for (var i = 0; i < node.children.length; i++) {
if (hasPathToSum(node.children[i], targetSum - node.val)) {
return true;
}
}
return false;
};
var tree1 = new Tree(5);
tree1.children.push(new Tree(4));
tree1.children.push(new Tree(6));
tree1.children.push(new Tree(7));
tree1.children[0].children.push(new Tree(10));
tree1.children[0].children.push(new Tree(20));
tree1.children[1].children.push(new Tree(3));
tree1.children[1].children.push(new Tree(2));
tree1.children[2].children.push(new Tree(50));
tree1.children[2].children.push(new Tree(30));
// 5
// 4 6 7
// 10 20 3 2 50 30
console.log(hasPathToSum(tree1, 19)); //true
console.log(hasPathToSum(tree1, 13)); // true
console.log(hasPathToSum(tree1, 42)); // true
console.log(hasPathToSum(tree1, 14)); // true
console.log(hasPathToSum(tree1, 1)); // false
console.log(hasPathToSum(tree1, 99)); // false
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment