バイナリ検索ツリーを実現するJava

バイナリ検索ツリー

1.定義

ここに画像を挿入説明

  1. 左の部分木が空でない場合、その後、すべてのノードは、以下にその根の値よりも左の部分木の値です
  2. 右サブツリーが空でない場合、右サブツリー・ノードは、そのルートの値より大きいすべての値であります
  3. 左と右のサブツリーはまた、二分探索木です
  4. これは、ノードのキーと等しくありません

2.削除チェック

2.1挿入

ここに画像を挿入説明

 public void insert(T val) {
    if (val == null)
        throw new NullPointerException();
    root = insert(val, root);
}

/**
 * 插入方法的实际执行
 */
private Node<T> insert(T val, Node<T> t) {
    if (root == null) {
        return new Node<>(val, null, null);
    }
    int compareRes = val.compareTo(root.value);
    if (compareRes > 0) {
        root.right = insert(val, root.right);
    } else if (compareRes < 0) {
        root.left = insert(val, root.left);
    }
    return t;
}

2.2検索

ツリーは、この値が含まれている検索

/**
 * 查看二叉树中是否包含此值
 */
public boolean contains(T val) {
    if (val == null) {
        throw new NullPointerException();
    }
    return contains(val, root);
}
private boolean contains(T val, Node<T> t) {
    if (t == null) {
        return false;
    }
    int compareRes = val.compareTo(t.value);
    if (compareRes > 0) {
        return contains(val, t.right);
    } else if (compareRes < 0) {
        return contains(val, t.left);
    } else {
        return true;
    }
}

2.3の最大値を探します

/**
 * 获取最大值
 */
public T findMax() {
    if (root == null) {
        return null;
    }
    return findMax(root).value;
}
private Node<T> findMax(Node<T> t) {
    while (t.right != null)
        t = t.right;
    return t;

2.4の最小値を探します

/**
 * 获取最小值
 */
public T findMin() {
    if (root == null) {
        return null;
    }
    return findMin(root).value;
}
private Node<T> findMin(Node<T> t) {
    while (t.left != null) {
        t = t.left;
    }
    return t;
}

2.5削除

ここに画像を挿入説明

public Node<T> delete(T val) {
    if (val == null)
        throw new NullPointerException();
    return delete(val, root);
}
private Node<T> delete(T val, Node<T> t) {
    if (t == null)
        return null;
    int compareRes = val.compareTo(t.value);
    if (compareRes > 0)
        delete(val, t.right);
    else if (compareRes < 0)
        delete(val, t.left);
    else if (t.left != null && t.right != null) {
        Node<T> temp = findMin(t.right);
        t.value = temp.value;
        delete(val,temp);
    }else
        t = (t.left ==null ? t.right:t.left);
    return t;
}
公開された17元の記事 ウォンの賞賛1 ビュー649

おすすめ

転載: blog.csdn.net/c_c_y_CC/article/details/103498959