Skip to content

Instantly share code, notes, and snippets.

@alexitaylor
Last active May 4, 2017 16:50
Show Gist options
  • Save alexitaylor/6380d291b7c58a2657f84cf6c5f94824 to your computer and use it in GitHub Desktop.
Save alexitaylor/6380d291b7c58a2657f84cf6c5f94824 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 BinaryTree = function(value) {
this.value = value;
this.left = null;
this.right = null;
}
BinaryTree.prototype.insert = function(value) {
let node = new BinaryTree(value);
function recurs(BT) {
if (BT.value <= value && BT.right === null) {
BT.right = node;
} else if (BT.value <= value) {
recurs(BT.right);
} else if (BT.value >= value && BT.left === null) {
BT.left = node;
} else if (BT.value >= value) {
recurs(BT.left);
}
}
recurs(this);
}
const hasPathToSum = function(node, targetSum) {
// your code here
if (targetSum === 0 && node.left === null && node.right === null) {
return true
} else {
let result = false
let subSum = targetSum - node.value
if (subSum === 0 && node.left === null && node.right === null) {
return true;
} else if (node.left !== null) {
result = result || hasPathToSum(node.left, subSum);
} else if (node.right !== null) {
result = result || hasPathToSum(node.right, subSum);
}
return result
}
};
let newTree = new BinaryTree(6);
newTree.insert(1)
newTree.insert(2)
newTree.insert(2)
// console.log(newTree);
console.log(hasPathToSum(newTree, 9))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment