给定一棵二叉树,确定它是否是一个有效的二叉搜索树(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);
}
本文介绍了一种检查给定二叉树是否为有效二叉搜索树(BST)的方法。BST是一种特殊的二叉树,其每个节点的左子树只包含小于节点键的键,右子树只包含大于节点键的键,且左右子树也必须是BST。通过遍历树并检查每个节点的键相对于其子节点键的大小,可以确定整个树是否符合BST的定义。
271

被折叠的 条评论
为什么被折叠?



