如何使这种二叉树插入方法起作用

时间:2019-06-08 08:09:14

标签: java insert boolean binary-tree binary-search-tree

我正在二叉搜索树中实现不同的方法,并且由于似乎不起作用而被卡在insert方法上。

一段时间以来,我一直在尝试实现insert方法,但似乎无济于事,它总是返回null。此方法需要一个用户并将其添加到数据库。使用User类。

    public boolean beFriend(User friend) throws IllegalArgumentException {
    User node = friend;
    if (friend == null) {
        throw new IllegalArgumentException();

    }
    if(root == friend) {
        return false;
    } else if(root.getKey() < friend.getKey()) {
        if(root.getLeft() != null) {
            root.setLeft(friend);
            return true;
        } else {
            root.setLeft(node);
            return true;
        }
    } else { if(root.getRight() != null) {
            root.setRight(friend);
        } else {
            root.setRight(node);
            return true;
        }
    }
    return false;
    }

我希望将User朋友添加到数据库中并输出其详细信息,但是我当前得到的输出为null。

1 个答案:

答案 0 :(得分:0)

您没有在方法中定义“ root”,因此它始终为null。您应该定义“ root”以与朋友进行比较并从中获取任何数据。