I have written the following code to check if a tree is a Binary search tree. Please help me check the code:
Okay! The code is edited now. This simple solution was sugge
We do a depth-first walk through the tree, testing each node for validity as we go. A given node is valid if it's greater than all the ancestral nodes it's in the right sub-tree of and less than all the ancestral nodes it's in the left-subtree of. Instead of keeping track of each ancestor to check these inequalities, we just check the largest number it must be greater than (its lowerBound) and the smallest number it must be less than (its upperBound).
import java.util.Stack;
final int MIN_INT = Integer.MIN_VALUE;
final int MAX_INT = Integer.MAX_VALUE;
public class NodeBounds {
BinaryTreeNode node;
int lowerBound;
int upperBound;
public NodeBounds(BinaryTreeNode node, int lowerBound, int upperBound) {
this.node = node;
this.lowerBound = lowerBound;
this.upperBound = upperBound;
}
}
public boolean bstChecker(BinaryTreeNode root) {
// start at the root, with an arbitrarily low lower bound
// and an arbitrarily high upper bound
Stack stack = new Stack();
stack.push(new NodeBounds(root, MIN_INT, MAX_INT));
// depth-first traversal
while (!stack.empty()) {
NodeBounds nb = stack.pop();
BinaryTreeNode node = nb.node;
int lowerBound = nb.lowerBound;
int upperBound = nb.upperBound;
// if this node is invalid, we return false right away
if ((node.value < lowerBound) || (node.value > upperBound)) {
return false;
}
if (node.left != null) {
// this node must be less than the current node
stack.push(new NodeBounds(node.left, lowerBound, node.value));
}
if (node.right != null) {
// this node must be greater than the current node
stack.push(new NodeBounds(node.right, node.value, upperBound));
}
}
// if none of the nodes were invalid, return true
// (at this point we have checked all nodes)
return true;
}