Last active
March 10, 2019 02:18
-
-
Save lucas-janon/0decfbb55dfcd6c947cf524912a45acd to your computer and use it in GitHub Desktop.
Best algorithm to validate binary search trees
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
/** | |
* The logic is the following: first call: no parents, then the node can have any value | |
* then it goes down recursively on both left and right nodes, checking that left.value < node.value & right.value > node.value | |
* but the magic is the following, and it's where most algorithms fail (or use much more computation than this one): | |
* in the recursive call involving the left node, the algorithm sets a maximum value to subsequent recursive calls, so when the left node | |
* calls validateTree on its right node, that right node is forced to not just being higher than its parent but also | |
* being lower than the parent of its parent, because remember that a binary search tree can't have any direct or indirect higher value | |
* on its left. The same logic is applied to its right, but of course with a minimum value. | |
*/ | |
const validateTree = (node, min = Number.MIN_SAFE_INTEGER, max = Number.MAX_SAFE_INTEGER) => { | |
if (!node) { | |
return true; | |
} else { | |
return node.value > min && node.value < max && validateTree(node.left, min, node.value) && validateTree(node.right, node.value, max) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment