【发布时间】:2021-06-02 18:54:51
【问题描述】:
您好,我是初学者,现在正在学习 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;
}
}
【问题讨论】:
标签: data-structures graph tree binary-search-tree dsa