Skip to content

Instantly share code, notes, and snippets.

@M-Shehu
Created March 28, 2019 16:37
Show Gist options
  • Save M-Shehu/357216639cf29dd6c35cc9385e298883 to your computer and use it in GitHub Desktop.
Save M-Shehu/357216639cf29dd6c35cc9385e298883 to your computer and use it in GitHub Desktop.
Given some target sum, the function returns 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, targetSum) {
// your code here
let isTotal = null;
if (targetSum === node.value) {
return true;
} else {
if (node.left === null && node.right === null) {
return false;
}
if (node.right) {
isTotal = hasPathToSum(node.right, targetSum - node.value);
}
if (isTotal === false && node.left) {
isTotal = hasPathToSum(node.left, targetSum - node.value);
}
return isTotal;
}
};
class BinarySearchTree {
constructor(value) {
this.value = value;
this.left = null;
this.right = null;
}
insert(node) {
if (node === this.value) {
return 'Already In The Tree';
}
var compare = node > this.value;
if (compare) {
if (this.right === null) {
this.right = new BinarySearchTree(node);
} else {
return this.right.insert(node); // recursively searching down tree to properly insert node; Added return keyword to test adding in duplicate values
}
} else {
if (this.left === null) {
this.left = new BinarySearchTree(node);
} else {
return this.left.insert(node);
}
}
}
}
var node = new BinarySearchTree(10);
node.insert(8);
node.insert(11);
node.insert(7);
node.insert(9);
node.insert(15);
node.insert(13);
node.insert(16);
console.log(hasPathToSum(node, 300)); // false
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment