搜索树 二分搜索

版权声明:本文全部是胡说八道,如果你喜欢,可随意转载 https://blog.csdn.net/robinsongsog/article/details/79944624

二叉树主要应用在搜索,假设我们把数据存储在二叉树的节点里面,为了简单起见,这里的数据就存一个整数

把一个普通的二叉树变成一个二叉搜索树,那么就是让这个树的左子树的每一个节点都比这个节点小,右子树的每一个节点都比这个节点大。这就表明,数中所有成员可以按照一种特定的方法将其排序。

我们现在给出二叉搜索树的一些常见操作,二叉搜索树需要所有的成员能够被排序,写一个通用类,我们需要提供一个能够描述这些属性的接口,compareTo 方法使用于每个成员,注意,我们一般不用equal 这个方法,反而,两个items equal 当且仅当 compareTo 方法返回0

private static class BinaryNode<AnyType>
{
    // Constructors
    BinaryNode(AnyType theElement)
    {this (theElement, null, null); }

    BinaryNode(AnyType theElement, BinaryNode<AnyType> lt, BinaryNode<AnyTpe> rt)

    AnyType element;             // the data in the node
    BinaryNode<AnyType>  left;   // left child;
    BinaryNode<AnyType> right;   // Right child
}

上述代码描述二叉搜索树的结构, 唯一的一个成员变量是对根节点的引用,当树为空时,这个引用为NULL



包含 (contains)

这个操作(operation) 返回true, 当树中包含X

public class BinarySearchTree<AnyType extends Comparable < ? super AnyType>>
{
    private static class BinaryNode<AnyType>

    private binaryNode<Anytype> root;

    public binarySearchTree()
       { root = null; }

    public boolean isEmpty()
       { return root = null; }

    public boolean contains(AnyType x)
       { return contains(x, root); }

    public AnyType findMin()
       { if (isEmpty()) throw new UnderflowException();
            return findMin(root).element;
       }

    public AnyType findMax()
       { if (isEmpty()) throw new UnderflowException();
            return findMax(root).element;
       }
    public void insert(AnyType x)
       {    root = insert(x, root); }
    public void remove(AnyType x)
       {    root = remove(x, root); }
    

    



猜你喜欢

转载自blog.csdn.net/robinsongsog/article/details/79944624
今日推荐