# Can anyone tell me what's wrong with my code?

• ``````public class Solution {
public boolean isValidBST(TreeNode root) {
if(root!=null){
if(root.left!=null){
if(root.left.val>=root.val){
return false;
}
}
if(root.right!=null){
if(root.right.val<=root.val){
return false;
}
}
return isValidBST(root.left)&&isValidBST(root.right);
}
return true;
}
``````

}

• What did the judge say? Time Limit Exceed? Compile Error? Runtime Error? Wrong answer? If you don't give us the information to start with, it is much more difficult to help.

• What your code basically says is: A tree is a BST iff

``````1. (left child) <= root <= (right child), and
2. both left and right subtree are BST.
``````

This logic does not work for the following tree:

{5, 3, #, 2, 8}

because

{5 3 #} satisfies condition 1, and both {3, 2, 8} and {#} are BSTs (condition 2). So your code would return true, but it is not a BST.

The reason is that your code only checks for contradicted values that are NEIGHBOURS. However, the contradiction could happen anywhere. Please reconsider the logic of your code.

• it is wrong answer. I am wondering if there is a way to correct my code or my thought is totally wrong

• you need compare the root value with the biggest of left sub tree and smallest of right tree.

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.