I'm trying to solve this problem but I'm having some troubles:
In a binary search tree (BST):
- The data value of every node in a node's left subtree is less than the data value of that node.
- The data value of every node in a node's right subtree is greater than the data value of that node.
Given the root node:
class Node { int data; Node left; Node right; }
Determine if the binary tree is also a binary search tree
I have this code:
boolean check(Node root) {
//node doesn't have any children
if (root.left == null && root.right == null) {
return true;
}
boolean leftIsBst = true;
boolean rightIsBst = true;
if (root.left != null) {
leftIsBst = (root.left.data < root.data) && check(root.left);
}
if (root.right != null) {
rightIsBst = (root.right.data > root.data) && check(root.right);
}
return leftIsBst && rightIsBst;
}
This is working in some cases, but it fails in cases like this one:
As you see, node (4) is in the node (3)'s left subtree, although 4 is greater than 3, so the method should return false
. My code returns true
, though.
How could I control that case? How can I check that all the values in the left/right subtree are lower/greater than the root (not only the direct child)?