Example 2:
5
/ \
1 4
/ \
3 6
Input: [5,1,4,null,null,3,6]
Output: false
Explanation: The root node's value is 5 but its right child's value is 4
- 注意!不止要满足root以及左右节点的关系,要考虑root和左右子树的关系!
- long 引入:Long.MIN_VALUE,Long.MAX_VALUE
class Solution {
public boolean isValidBST(TreeNode root) {
return sub(root,Long.MIN_VALUE,Long.MAX_VALUE);
}
boolean sub(TreeNode root,long min,long max){
if(root==null){
return true;
}
if(root.val<=min||root.val>=max){
return false;
}
return sub(root.left,min,root.val)&&sub(root.right,root.val,max);
}
}