Last active
May 14, 2021 02:23
-
-
Save jameslockwood/918941d6eff012f97a461388d6f6f8c8 to your computer and use it in GitHub Desktop.
Binary Search Tree algorithms
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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