javasearchdata-structurestreebinary

inserting in binary tree doesn't work using java


I'm currently learning about trees using java and i have some errors going on here in the insertion of items in a binary tree I don't why it doesn't work

this is the code: tree node:

public class TNode {
    int data;
    TNode left;
    TNode right;

    public TNode(int data) {
        this.data = data;
        left = null;
        right = null;
    }
}

tree class:

public class Tree {
    TNode root;

    public Tree(){
        root = null;
    }

    public TNode insertNode(TNode item, int d) {
        if (item == null) {
            return new TNode(d);
        }

         if (d < item.data) {
            item.left = insertNode(item, d);
        }

        if (d > item.data) {
            item.right = insertNode(item, d);
        } else {
            return item;
        }

        return item;
    }

    public void add(int d) {
        insertNode(root, d);
    }
}

Whenever I add an item the root remains null with no right or left items if someone can help I'll be really thankful


Solution

  • root is always null because you never assign value to it.

    you can add to the beginning of your method check and assign it

    public TNode insertNode(TNode item, int d){
        if(item == null){
            TNode node = new TNode(d);
            if (root == null) { 
                root = node;
            }
            return node
        }
        ... rest of method isn't changed...
    

    Also when you are recursing you should make a call with a proper child node instead of always calling with item, so for example first case would be:

        item.left = insertNode(item.left, d);
    

    For second case you would just use item.right instead.