【发布时间】:2018-05-16 12:30:32
【问题描述】:
我正在尝试解决这个问题,但我遇到了一些麻烦:
在二叉搜索树 (BST) 中:
- 节点左子树中每个节点的数据值都小于该节点的数据值。
- 节点右子树中每个节点的数据值都大于该节点的数据值。
给定根节点:
class Node { int data; Node left; Node right; }判断二叉树是否也是二叉搜索树
我有这个代码:
boolean check(Node root) {
//node doesn't have any children
if (root.left == null && root.right == null) {
return true;
}
boolean leftIsBst = true;
boolean rightIsBst = true;
if (root.left != null) {
leftIsBst = (root.left.data < root.data) && check(root.left);
}
if (root.right != null) {
rightIsBst = (root.right.data > root.data) && check(root.right);
}
return leftIsBst && rightIsBst;
}
这在某些情况下有效,但在这种情况下会失败:
如你所见,节点(4)在节点(3)的左子树中,虽然4大于3,所以该方法应该返回@ 987654325@。不过,我的代码返回 true。
我该如何控制这种情况?如何检查左/右子树中的所有值是否小于/大于根(不仅是直接子树)?
【问题讨论】:
标签: java algorithm binary-tree binary-search-tree