Search code examples
javarecursionlinked-listbinary-search-treenodes

How to assign a node to be the prev node in java?


I am working on a binary search tree. I have a previous node and a node. The previous node comes before the node. I need help assigning that previous node.

Here is my block of code:

private BSTNode<E> add(BSTNode<E> node, E value, BSTNode<E> parent, BSTNode<E> prev)
{
    if (node == null)
    {
        node = new BSTNode<E>(value);
        node.parent = parent;

       //issue takes place here. 
        node.next = node;
        node = prev;

        this.numElements++;
    }
    else if (node.data.compareTo(value) > 0)
    {
        node.left = add(node.left, value, node , getPrevNode(node));
    }
    else if (node.data.compareTo(value) < 0)
    {
        node.right = add(node.right, value, node, node.parent);
    }
    return node;
}

It's inside this class

public class BinarySearchTree<E extends Comparable<E>>
{
private BSTNode<E> root; // root of overall tree
private int numElements;
private BSTNode<E> first;
// post: constructs an empty search tree
public BinarySearchTree()
{
    this.root = null;
    this.numElements = 0;
}

private static class BSTNode<E>
{
    public E data;
    public BSTNode<E> left;
    public BSTNode<E> right;
    public BSTNode<E> parent;
    public BSTNode<E> next;

    public BSTNode(E data)
    {
        this(data, null, null, null, null);
    }

    public BSTNode(E data, BSTNode<E> left, BSTNode<E> right, BSTNode<E> parent, BSTNode<E> next)
    {
        this.data = data;
        this.left = left;
        this.right = right;
        this.parent = parent;
        this.next = next;
    }
 }
}

I would try to have this solved using recursion, but drop down the ideas, because I am uncertain on how to solve this. I've tried several ways, but none of it works.


Solution

  • Found the answer I was looking for, it was just this

    if(prev == null)
            {
                node.next = parent;
            }
            else
            {
                node.next = prev.next;
                prev.next = node;
            }