check if a given binary tree is bst or not code example
Example 1: check if binary search tree is valid
class BTNode {
constructor(value) {
this.value = value;
this.left = null;
this.right = null;
}
}
const isBinarySearchTree = (tree) => {
if (tree) {
if (
tree.left &&
(tree.left.value > tree.value || !isBinarySearchTree(tree.left))
) {
return false;
}
if (
tree.right &&
(tree.right.value <= tree.value || !isBinarySearchTree(tree.right))
) {
return false;
}
}
return true;
};
Example 2: how to check if a binary tree is a binary search tree
how to check if a binary tree is a binary search tree