代码之家  ›  专栏  ›  技术社区  ›  Adan Vivero

如何分配一个节点作为Java中的PREV节点?

  •  0
  • Adan Vivero  · 技术社区  · 6 年前

    我正在研究一个二进制搜索树。我有一个前一个节点和一个节点。前一个节点位于节点之前。我需要分配前一个节点的帮助。

    这是我的代码块:

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

    我会尝试使用递归来解决这个问题,但是放弃这些想法,因为我不确定如何解决这个问题。我试过几种方法,但都不管用。

    0 回复  |  直到 6 年前
        1
  •  0
  •   Adan Vivero    6 年前

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

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