I wrote a Java method (along with a private class) to check if a binary tree is also a binary search tree (BST). I would like some feedback on the design of my solution. Here is a brief description and the code is provided below it :
Do a depth-first traversal of the tree and test if each node satisfies the binary search tree property. The binary search tree property states that a node is valid if its key is greater than every ancestral node in whose right-subtree it resides and less than every ancestral node in whose left-subtree it resides. Instead of checking the node against all of its ancestors, simply check the largest number it should be greater than (its lower bound) and the smallest number it should be less than (its upper bound).
private class Bounds {
Node node;
int min_bound;
int max_bound;
}
public boolean check_if_valid_binary_search_tree(Node node) {
if (node == null) return true;
Deque<Bounds> stack = new ArrayDeque<Bounds>();
Bounds bounds = new Bounds();
bounds.node = node;
bounds.max_bound = Integer.MAX_VALUE;
bounds.min_bound = Integer.MIN_VALUE;
stack.push(bounds);
while (!stack.isEmpty()) {
bounds = stack.pop();
Node curr_node = bounds.node;
int lower_bound = bounds.min_bound;
int upper_bound = bounds.max_bound;
if (curr_node.val < lower_bound || curr_node.val > upper_bound) return false;
if (curr_node.left != null) {
Bounds left = new Bounds();
left.node = curr_node.left;
left.max_bound = curr_node.val;
left.min_bound = lower_bound;
stack.push(left);
}
if (curr_node.right != null) {
Bounds right = new Bounds();
right.node = curr_node.right;
right.min_bound = curr_node.val;
right.max_bound = upper_bound;
stack.push(right);
}
}
return true;
}
Note : The approach I use is modelled after a solution written in python by Parker Phinney (of Interview Cake) to the problem of checking if a binary tree is a valid BST.
I would like [feedback] on the design of my solution
- I see no design. Two approaches come to (my) mind re. check binary tree for BSearchT: inorder traversal and _ both sub-trees BST and root between left and right sub-tree_. You do not motivate handling the stack explicitly. \$\endgroup\$interface
, a short description with an external reference - hey, even UML will do nicely. \$\endgroup\$