Recursive Binary Search Tree Insert

Posted by Nick Sinklier on Stack Overflow See other posts from Stack Overflow or by Nick Sinklier
Published on 2013-02-12T04:41:34Z Indexed on 2013/11/13 9:54 UTC
Read the original article Hit count: 266

Filed under:
|

So this is my first java program, but I've done c++ for a few years. I wrote what I think should work, but in fact it does not. So I had a stipulation of having to write a method for this call:

tree.insertNode(value);

where value is an int. I wanted to write it recursively, for obvious reasons, so I had to do a work around:

public void insertNode(int key) {
    Node temp = new Node(key);

    if(root == null) root = temp;

    else insertNode(temp);
}

public void insertNode(Node temp) {
    if(root == null)
        root = temp;

    else if(temp.getKey() <= root.getKey())
        insertNode(root.getLeft());

    else insertNode(root.getRight());
}

Thanks for any advice.

© Stack Overflow or respective owner

Related posts about java

Related posts about binary-search-tree