给定一棵二叉树,确定它是否是一个有效的二叉搜索树(BST)。
BST的定义如下:
节点的左子树只包含小于节点键的键节点。
节点的右子树只包含大于节点键的键节点。
左和右子树都必须是二叉搜索树。
Example 1:
Input: 2 / \ 1 3 Output: true
Example 2:
5 / \ 1 4 / \ 3 6 Output: false
public boolean isValidBST(TreeNode root) {
if (root == null) {
return true;
}
if (root.left != null) {
TreeNode cur = root.left;
while (cur.right != null) {
cur = cur.right;
}
if (cur.val >= root.val) {
return false;
}
}
if (root.right != null) {
TreeNode cur = root.right;
while (cur.left != null) {
cur = cur.left;
}
if (cur.val <= root.val) {
return false;
}
}
return isValidBST(root.left) && isValidBST(root.right);
}