0

我正在编写二叉树搜索。当我尝试抛出重复异常时出现错误。我不明白这是为什么。我的源链接是: http: //pages.cs.wisc.edu/~vernon/cs367/notes/9.BST.html

资源:

class BinaryTreenode {
// *** fields ***
private Comparable key;
private BinaryTreenode left, right;

// *** methods ***

// constructor
public BinaryTreenode(Comparable k, BinaryTreenode l, BinaryTreenode r) {
   key = k;
   left = l;
   right = r;
}

 // access to fields
public Comparable getKey() {return key;}
public BinaryTreenode getLeft() {return left;}
public BinaryTreenode getRight() {return right;}

// change fields
public void setKey(Comparable k) {key = k;}
public void setLeft(BinaryTreenode l) {left = l;}
public void setRight(BinaryTreenode r) {right = r;}
 }

class BST {
// *** fields ***
private BinaryTreenode root; // ptr to the root of the BST

// *** methods ***
public BST() { root = null; } // constructor
public void insert(Comparable key) throws DuplicateException {...}
  // add key to this BST; error if it is already there
public void delete(Comparable key) {...}
  // remove the node containing key from this BST if it is there;
  // otherwise, do nothing
public boolean lookup(Comparable key) {...}
 // if key is in this BST, return true; otherwise, return false
public void print(PrintWriter p) {...}
 // print the values in this BST in sorted order (to p)
}

在我的插入方法中,我收到一个错误这是我的代码:

public class BinaryTreeNode 
{
// ***fields***
private Comparable key;
private BinaryTreeNode left;
private BinaryTreeNode right;

// ***methods***
// constructor
public BinaryTreeNode(Comparable k, BinaryTreeNode l, BinaryTreeNode r)
{
    key = k;
    left = l;
    right = r;
}

public Comparable getKey()
{
    return key;
}

public BinaryTreeNode getLeft()
{
    return left;
}

public BinaryTreeNode getRight()
{
    return right;
}

public void setKey(Comparable k)
{
    key = k;
}

public void setLeft(BinaryTreeNode l)
{
    left = l;
}

public void setRight(BinaryTreeNode r)
{
    right = r;
}

}

class BST
{
// ***fields***
private BinaryTreeNode root;

// ***methods**
// constructor
public BST()
{
    root = null;
}

public void insert(Comparable key) throws DuplicateException
{
    if (root.getKey() != null) throw new DuplicateException;
}
}
4

1 回答 1

0

如果您希望每个节点都有一个唯一的键,则必须检查整个树,而不仅仅是根。所以这将是一个更好的检查方法:

public void insert(Comparable key) throws DuplicateException
{
    // Make sure key is not already in tree
    if(this.lookup(key))
        throw new DuplicateException;
    // Find correct position in tree to insert the new node

    // Insert the new node

}

在您当前的代码中class BSTroot始终是null. 因此,您应该在调用root.getKey().

于 2013-09-12T07:58:51.640 回答