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
UPDATE: I just saw that this solution was suggested before. Sorry about this guys, maybe somebody still finds my version useful
Here is a solution that uses In-Order Traversal to check for BST property. Before I provide the solution, I am using a definition of a BST that doesn't allow duplicates. This means that each value in the BST is unique (this is just for simplicity).
Code for recursive inorder print:
void printInorder(Node root) {
if(root == null) { // base case
return;
}
printInorder(root.left); // go left
System.out.print(root.data + " "); // process (print) data
printInorder(root.right); // go right
}
After this inorder traversal on a BST, all the data should be printed in sorted ascending order. For example the tree:
5
3 7
1 2 6 9
would have inorder print:
1 2 3 5 6 7 9
Now, instead of printing the node, we can keep track of the previous value in the In-Order sequence and compare it to the current node's value. If the current node's value is smaller than the previous value, this means that the sequence isn't in the ascending sorted order and that the BST property is violated.
For example, the tree:
5
3 7
1 8 6 9
Has a violation. The right child of 3 is 8 and this would be ok if 3 was the root node. However, in a BST 8 would end up as a left child of 9 and not as a right child of 3. Therefore, this tree is not a BST. So, the code that follow this idea:
/* wrapper that keeps track of the previous value */
class PrevWrapper {
int data = Integer.MIN_VALUE;
}
boolean isBST(Node root, PrevWrapper prev) {
/* base case: we reached null*/
if (root == null) {
return true;
}
if(!isBST(root.left, prev)) {
return false;
}
/* If previous in-order node's data is larger than
* current node's data, BST property is violated */
if (prev.data > root.data) {
return false;
}
/* set the previous in-order data to the current node's data*/
prev.data = root.data;
return isBST(root.right, prev);
}
boolean isBST(Node root) {
return isBST(root, new PrevWrapper());
}
The in-order traversal for the sample tree would fail the check for node 5 since previous in-order of 5 is 8, which is larger so BST property is violated.