简体   繁体   English

二进制搜索树更改插入方法返回类型

[英]Binary search tree change insert method return type

I wrote an insert method for a binary search tree that is void . 我为void的二叉搜索树编写了一个insert方法。 I have to change that method so that it returns a boolean but I am confused because my helper method for insert returns a Node . 我必须更改该方法,以便它返回boolean但是我感到困惑,因为我用于插入的助手方法返回了Node

Is there a way to write some other helper method that will return a boolean ? 有没有一种方法可以编写其他一些返回boolean帮助器方法? If not, how would I go about changing my method to return a boolean ? 如果没有,我将如何更改我的方法以返回boolean

This is my method: 这是我的方法:

public void insert(E s) 
{
    root = insert(s, root);
    root.setParent(findParent(root.getData()));
} 

private Node<E> insert(E s, Node<E> T)
{
    //easiest case, empty tree, create new tree
    if(T == null)
    {
        T = new Node<E>(s);
    }
    //s is greater than T, insert on right subtree
    else if(s.compareTo(T.getData()) > 0)
    {
        T.setRight(insert(s, T.getRight()));
    }
    //s is less than T, insert on left subtree
    else if (s.compareTo(T.getData()) < 0)
    {
        T.setLeft(insert(s,T.getLeft()));
    }
    else
    {
        System.out.println("Item already present.");

    }
    return T;
}//Close insert

I'm assuming you're supposed to return true if the insert is successful and false otherwise? 我假设如果插入成功,您应该返回true ,否则返回false Change your first insert function to look like this: 更改您的第一个insert函数,如下所示:

public boolean insert(E s) 
{
    try {
        root = insert(s, root);
        root.setParent(findParent(root.getData()));
        return true;
    } catch (Exception e) {
        return false;
    }
}

And change your helper function so that if the item is already present, it throws an Exception (for the main insert function to catch and trigger the false return). 并更改您的辅助函数,以便如果该项目已经存在,则将引发Exception(供主insert函数捕获并触发false返回)。

private Node<E> insert(E s, Node<E> T) throws Exception {
    ...
    else {
        System.out.println("Item already present.");
        throw new Exception("Item already present.");
    }
    return T;
}

Or (as Tutankhamen suggests) return null from the helper method in the case of an unsuccessful insertion, so you have: 或者 (如Tutankhamen所建议的那样)在不成功插入的情况下从helper方法返回null ,因此您具有:

public boolean insert(E s) 
{
    root = insert(s, root);
    if (root == null) {
        return false;
    }
    root.setParent(findParent(root.getData()));
    return true;
}

private Node<E> insert(E s, Node<E> T) {
    ...
    else {
        System.out.println("Item already present.");
        return null;
    }
    return T;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM