Jenna Han
Jenna Han

Reputation: 13

Recursive Insert for Binary Tree

I'm working on code for insertion into a binary search tree. It works for the first node I insert, making it the root, but after that it doesn't seem to insert any nodes. I'm sure it's a problem with setting left/right references, but I can't quite figure it out. Please help!

    //params: key of node to be inserted, parent node
    public void insert(int newKey, TreeNode parent){

    //if the root of the tree is empty, insert at root
    if(this.getRoot() == null){
        this.root = new TreeNode(newKey, null, null);
    }

    //if the node is null, insert at this node
    else if(parent == null)
        parent = new TreeNode(newKey, null, null);


    else{
        //if the value is less than the value of the current node, call insert on the node's left child
        if(newKey < parent.getKey()) {
                insert(newKey, parent.getLeft());
        }
        //greater than value of current node, call insert on node's right child
        else if(newKey > parent.getKey()){
                insert(newKey, parent.getRight());
        }
        //same as value of current node, increment iteration field by one
        else if(newKey == parent.getKey())
            parent.incrementIterations();
    }

}

My treenodes have key, left, right, and iteration fields, as well as getter/setter functions. Thank you in advance!

Upvotes: 1

Views: 16343

Answers (3)

Soumadip Dey
Soumadip Dey

Reputation: 77

private AVLNode insert(AVLNode root, int value){
    if (root == null) return new AVLNode(value);

    if(root.value > value)
        root.leftChild = insert(root.rightChild, value);
    else
        root.rightChild = insert(root.leftChild, value);

    return root;
}

Upvotes: 1

user892871
user892871

Reputation: 1025

public Node insertNode(Node head, int data) {

        if(head == null){
            head = new Node();
            head.data = data;
            return head;
        }
        if(head.data < data) {
            head.right = insertNode(head.right,data);
        } else {
            head.left = insertNode(head.left, data);
        }
        return head;
    }

Upvotes: 10

Ajay Karthik
Ajay Karthik

Reputation: 41

If (parent==null) you are creating a node, but you are not associating it to tree back. Its just created and garbage collected.

You should be using insert (newkey, parent) then u still have handle to tree

Upvotes: 2

Related Questions