二叉查找树的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
今日推荐