I am trying to solve this problem, but I am having problems:
In the binary search tree (BST):
- The data value for each node in the left subtree of the node is less than the data value of this node.
- The data value for each node in the right subtree of the node is greater than the data value of this node.
Given the root of the node:
class Node {
int data;
Node left;
Node right;
}
Determine if a binary tree is also a binary search tree
I have this code:
boolean check(Node root) {
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;
}
In some cases, this works, but in such cases, it does not:

As you can see, node (4) is in the left subtree of node (3) , although 4 is greater than 3, so the method should return false. My code is returning true.
? , / /, ( )?