1

I am implementing different methods in a binary search tree and am stuck on the insert method as it just doesn't seem to work.

I have been trying to implement the insert method for a while now but nothing seems to work it's always returning null. This method takes a user and adds it to the database. Using the User class.

    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;
    }

I expect the User friend to be added to the database and output its details but the output that I am currently getting is null.

Anmol
  • 11
  • 2

1 Answers1

0

You don't define "root" in your method, therefore it's always null. You should define "root" to compare with friend and getting any data from it.

  • Hey @Bogachev_Ilia I tried what u recommended but still getting the same output. – Anmol Jun 08 '19 at 08:40
  • What are you expected from "root"? Is it another data from database? If yes, you should add it to your method like this:"public boolean beFriend(User friend, User root)" – Bogachev_Ilia Jun 08 '19 at 08:43
  • The root is set at top of the Binary search tree class as an instance variable public User root. I am supposed to add the new User friend in the database according to its key. – Anmol Jun 08 '19 at 08:52
  • review comment: adding a snippet showing the change would probably help the OP easily understand your answer. – Anuvrat Parashar Jun 08 '19 at 09:25