检查二叉树是否也是二叉搜索树的问题

时间:2017-12-02 15:55:49

标签: java algorithm binary-tree binary-search-tree

我正在尝试解决这个问题,但我遇到了一些麻烦:

  

在二叉搜索树(BST)中:

     
      
  • 节点左子树中每个节点的数据值小于该节点的数据值。
  •   
  • 节点右子树中每个节点的数据值都大于该节点的数据值。
  •   
     

给定根节点:

tar zxvf Ncurses_packageName.tar.gz
cd Ncurses_packageName
./configure
make
sudo make install
     

确定二叉树是否也是二叉搜索树

我有这段代码:

class Node {
    int data;
    Node left;
    Node right;
}

这在某些情况下有效,但在以下情况下失败:

enter image description here

如您所见,节点(4)位于节点(3)的左子树中,尽管4大于3,因此该方法应返回{ {1}}。不过,我的代码返回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 个答案:

答案 0 :(得分:6)

您的定义是正确的(尽管您不一定要坚持所有密钥都是不同的),但您的代码并未实现定义中的所有条件。具体而言,您不会在每个子树中强制执行最小值和最大值。

这是一个有效的递归解决方案,可以实现您的定义:

boolean check(Node root) {
    return check(root, INT_MIN, INT_MAX);
}
boolean check(Node n, int minval, int maxval) {
    if (n == null) {
        return true;
    }
    return (
        n.data >= minval && n.data <= maxval &&
        check(n.left, minval, n.data-1) &&
        check(n.right, n.data+1, maxval)
    );
}

请注意,我没有费心去检查n.data-1n.data+1中的溢出,这在现实生活中是必须要做的。如果您想允许重复的密钥,只需将其更改为n.data,您就不必担心了。

答案 1 :(得分:1)

以下内容应该有效

boolean check(Node root) {   

    if (root == null) {
        return true;
    }


    if (root.left != null && max(root.left) > root.data  ) {
        return false
    }

    if (root.right != null && max(root.right) < root.data ) {
        return false;
    }

    return check(root.left) && check(root.right);
}

注意:

  • 这是相当低效的
  • 您需要实施max()

答案 2 :(得分:1)

您的递归逻辑不正确。我在这里给cpp逻辑。您可能需要将其转换为Java代码。

bool check(Node * root){

static Node *prev = NULL;

if(root) {

    If(!check(root->left)) return false;

    If(prev != Null && prev->data > root->data) return false;

    Prev = root;

    return check(root->right);


}

return true;

}

答案 3 :(得分:0)

BST定义为:

- 节点的左子树始终包含值小于节点值的节点。   - 节点的右子树总是包含值大于节点值的节点。   - 左右子树也是有效的BST。

    class Solution {
        public boolean isValidBST(TreeNode root) {
            return helper (root,Integer.MIN_VALUE,Integer.MAX_VALUE);
        }
        public boolean helper(TreeNode root,long low,long high){
            if (root==null){
                return true;
            }
            if (root.val<low ||root.val>high){
                return false;
            }
            return (helper(root.left,low,root.val-1) && 
    helper(root.right,root.val+1,high));
        }
    }
相关问题