如何在Java中将节点分配为上一个节点?

时间:2019-05-01 02:33:22

标签: java recursion linked-list binary-search-tree nodes

我正在研究二叉搜索树。我有一个先前的节点和一个节点。前一个节点在该节点之前。我需要分配该先前节点的帮助。

这是我的代码块:

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;
}

它在此类之内

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;
    }
 }
}

我会尝试使用递归来解决此问题,但是请放弃想法,因为我不确定如何解决此问题。我已经尝试了几种方法,但是都没有用。

1 个答案:

答案 0 :(得分:0)

找到了我要找的答案,就是这个

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