A class that implements the Set interface using a binary search tree

The major hurdle is that our class does not implement Iterable. To overcome this, we augment the BinaryNode inner class by adding links to the next smallest and next largest nodes so that the iterator can efficiently return the next node (just like a linked list). Rewrite the insert method of MyBinarySearchTree to support the added links.

We first augment the data structure so that the inner class becomes:

     private   static   class  BinaryNode
    
{
         ...
        AnyType element;              
// The data in the node
        BinaryNode<AnyType> left;     // Left child
        BinaryNode<AnyType> right;    // Right child
        BinaryNode<AnyType> smaller;  // Previous in-order element
        BinaryNode<AnyType> larger;   // Next in-order element
    }

 

Here is the insert method:

private  BinaryNode < T >  insert(T x, BinaryNode < T >  t, BinaryNode < T >  larger, BinaryNode < T >  smaller)
{
    
if (t == null)
    
{
        BinaryNode
<T> n = new BinaryNode<T>(x, nullnull, larger, smaller);
        
if (larger != null) larger.prev = n;
        
if (smaller != null) smaller.next = n;
        
return n;
    }

    
int compareResult = x.compareTo(t.element);
    
if (compareResult < 0)
        t.left 
= insert(x, t.left, t, smaller);
    
else if (compareResult > 0)
        t.right 
= insert(x, t.right, larger, t);
    
else
        ; 
// duplicate

    
return t;
}


When a new node is inserted as a left child, three things must be done to support this augmentation: its larger field must point to its parent; its smaller field must be set to its parent's smaller field; and the parent's smaller field must be set to it. A similar triplet of changes is needed when the new node is a right child.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值