我不明白这怎么不是有效的 BST,有人可以解释一下吗?
I dont understand how this is not a valid BST, can someone explain?
Click for BST image
嗨,我是初学者,现在正在学习 DSA。该程序用于验证 bst。在所附的图像中,所有左节点都小于它们的根节点,所有右节点都大于它们的根节点。但是根据编译器(leet 代码),预期输出是错误的,我不明白为什么。有人可以向我解释一下吗?另外请在下面找到我的代码。
class Solution {
public boolean validatebst(TreeNode root){
System.out.println("Traversing "+ root.val);
if(root.left !=null && root.left.val > root.val)
return false;
else if(root.right != null && root.right.val < root.val){
return false;
}
return true;
}
public boolean checkbst(TreeNode root){
if(root == null)
return true;
if(!this.checkbst(root.left))
return false;
if(!this.validatebst(root))
return false;
if(!this.checkbst(root.right))
return false;
return true;
}
public boolean isValidBST(TreeNode root) {
if(this.checkbst(root))
return true;
return false;
}
}
树无效,因为右侧有一片叶子小于根。尽管它在其父项的左侧,这是正确的,但根右侧的所有内容都必须大于根。
https://dev.to/adityavardhancoder/what-is-a-valid-binary-search-tree-4kgj
link 中的示例 3 进行了说明,希望对您有所帮助 :)
Click for BST image
嗨,我是初学者,现在正在学习 DSA。该程序用于验证 bst。在所附的图像中,所有左节点都小于它们的根节点,所有右节点都大于它们的根节点。但是根据编译器(leet 代码),预期输出是错误的,我不明白为什么。有人可以向我解释一下吗?另外请在下面找到我的代码。
class Solution {
public boolean validatebst(TreeNode root){
System.out.println("Traversing "+ root.val);
if(root.left !=null && root.left.val > root.val)
return false;
else if(root.right != null && root.right.val < root.val){
return false;
}
return true;
}
public boolean checkbst(TreeNode root){
if(root == null)
return true;
if(!this.checkbst(root.left))
return false;
if(!this.validatebst(root))
return false;
if(!this.checkbst(root.right))
return false;
return true;
}
public boolean isValidBST(TreeNode root) {
if(this.checkbst(root))
return true;
return false;
}
}
树无效,因为右侧有一片叶子小于根。尽管它在其父项的左侧,这是正确的,但根右侧的所有内容都必须大于根。
https://dev.to/adityavardhancoder/what-is-a-valid-binary-search-tree-4kgj link 中的示例 3 进行了说明,希望对您有所帮助 :)