Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Binary Search Tree algorithms
function searchBinaryTree(tree, targetValue){
if(tree === null){
return null;
}
if(tree.value === targetValue){
return tree;
}
if(targetValue < tree.value){
return searchBinaryTree(tree.left, targetValue);
} else {
return searchBinaryTree(tree.right, targetValue);
}
}
function traverseBinaryTree(tree, fn){
if(tree !== null){
traverseBinaryTree(tree.left, fn);
fn(tree.value);
traverseBinaryTree(tree.right, fn);
}
}
function binaryTreeMin(tree){
if(tree === null){
return null;
}
return binaryTreeMin(tree.left) || tree.value;
}
function binaryTreeMax(tree){
if(tree === null){
return null;
}
return binaryTreeMin(tree.right) || tree.value;
}
function invertBinaryTree(tree){
if(tree == null){
return;
}
let temp = tree.left;
tree.left = tree.right;
tree.right = temp;
invertBinaryTree(tree.left);
invertBinaryTree(tree.right);
}
function isSameTree(a, b){
if(a === null & b === null){
return true;
}
if(a === null || b === null){
return false;
}
return (
a.value === b.value &&
isSameTree(a.left, b.left) &&
isSameTree(a.right, b.right)
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.