Search code examples
javabinary-search-tree

recursively adding an item to the BST


I am trying to make a method that will add items to a tree, and then I want to print this tree to the console. I have a class that I inherit and based on it I need to write the methods that I need:

public abstract class BinaryTreeNode {
    protected int data; // value stored in the node
    protected BinaryTreeNode left, right; // left and right sub-trees

    // constructor
    public BinaryTreeNode(int data) {
        this.data = data;
    }

    // recursively adds an item to the BST
    // @param new data to be stored in the new node
    public abstract void addBSTRecursion(int newNode);

    // prints the tree
    // for example, for a tree:
    //        7
    //    6        8
    // 2     7  4     9
    //
    // write:
    //
    //      2
    //   6
    //      7
    // 7
    //      4
    //   8
    //      9

    // method pseudocode
    //if there is a left subtree then print the left one (recursive call)
    //write out gaps (depending on level), write out data, go to new line
    //if it is right, print the right one (recursive call)
    //@param level the distance of the node from the root. We start from 0.
    public abstract void print(int level);

}

addBSTRecursion(int newNode) - recursively adds an item to the BST
print(int level) - if there is a left subtree then print the left one (recursive call), write out gaps (depending on level), write out data, go to new line, if it is right, print the right one (recursive call) Here's what I managed to do:

public class Node extends BinaryTreeNode {
    public Node(int data) {
        super(data);
    }

    @Override
    public void addBSTRecursion(int newNode) {
        if (data < this.data) {
            if (left != null) {
                left.addBSTRecursion(newNode);
            } else {
                left = new Node(newNode);
            }
        } else {
            if (right != null) {
                right.addBSTRecursion(newNode);
            } else {
                right = new Node(newNode);
            }
        }
    }

    @Override
    public void print(int level) {
        if(this.left != null)this.left.print(level+1);
        for(int n =0; n<level; n++) System.out.print(" ");
        System.out.println(data);
        if(this.right != null)this.right.print(level+1);
    }
}

My output:

10
 5
  14

I would like to receive:

   5
10
   14

Solution

  • This is always going to be false, since it compares this.data with itself:

        if (data < this.data) {
    

    It should be:

        if (newNode < this.data) {
    

    NB: calling the parameter newNode is misleading, as it is not a Node type, but an integer. Maybe call it newData.