Skip to content

Instantly share code, notes, and snippets.

@averylizette
Created October 10, 2019 16:58
Show Gist options
  • Select an option

  • Save averylizette/5dc2ee0d8a83502cb429e943eaf524ad to your computer and use it in GitHub Desktop.

Select an option

Save averylizette/5dc2ee0d8a83502cb429e943eaf524ad to your computer and use it in GitHub Desktop.
Binary Tree Interview Prompt With Tests
var findValue = (node, targetVal) => {
var result = false;
var accVal = node.value;
var checkNodes = (node) => {
if (!node.children) {
if (accVal === targetVal) {
result = true;
return;
} else {
return;
}
}
if (node.children) {
accVal += node.value;
node.children.forEach((child) => {
return checkNodes(child)
});
};
}
checkNodes(node);
return result;
}
function BinaryTree(value) {
this.value = value;
this.children = [];
this.addChild = addChild
}
var addChild = function(value, node) {
/*
transverse the tree until we find a node with one or less children
then instert this node into the child's array based on if it
is greater or less than the existing child's value (if there is a child)
*/
var child = new BinaryTree(value);
if (node.children.length === 0) {
node.children.push(child);
return;
} else if (node.children.length === 1) {
if (node.children[0].value > value) {
node.children.unshift(child);
return;
} if (node.children[0].value < value) {
node.children[0].push(child);
return;
} if (node.children[0].value === value) {
return node.addChild(node.children[0])
}
else if (node.children.length === 2) {
node.children.forEach((child) => {
return node.addChild(child)
});
}
}
}
var root = new BinaryTree(6);
root.addChild(4, root);
// root.addChild(2, root);
// root.addChild(-1, root);
// root.addChild(-6, root);
findValue(root, 10) //should return true
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment