数据结构|二叉搜索树及其常用操作

1. 定义

二叉搜索树是一种节点值之间具有一定数量级次序的二叉树,对于树中每个节点:

  • 若其左子树存在,则其左子树中每个节点的值都不大于该节点值;
  • 若其右子树存在,则其右子树中每个节点的值都不小于该节点值。
    数据结构|二叉搜索树及其常用操作_第1张图片

2. 常用操作

public class Node {
    public int key;
    public Node left;
    public Node right;

    public Node(int key){
        this.key = key;
    }
}

2.1 插入操作

public void insert(int key){
    if (root == null){
        root = new Node(key);
        return;
    }

    Node parent = null;
    Node cur = root;
    while (cur != null){
        if (key == cur.key){
            throw new RuntimeException("key 重复了: " + key);
        }else if (key < cur.key){
            parent = cur;
            cur = cur.left;
        }else {
            parent = cur;
            cur = cur.right;
        }
    }

    // cur 就是 key 要插入的位置
    Node node = new Node(key);
    if (key < parent.key){
        parent.left = node;
    }else {
        parent.right = node;
    }
}

2.2 删除操作

public boolean remove(int key){
    Node parent = null;
    Node cur = root;
    while (cur != null){
        if (key == cur.key){
            removeNode(parent, cur);
            return true;
        }else if (key < cur.key){
            parent = cur;
            cur = cur.left;
        }else {
            parent = cur;
            cur = cur.right;
        }
    }
    return false;
}

private void removeNode(Node parent, Node cur) {
    if (cur.left == null){
        if (cur == root){
            root = cur.right;
        }else if (cur == parent.left){
            parent.left = cur.right;
        }else {
            parent.right = root.right;
        }
    }else if (cur.right == null){
        if (cur == root){
            root = cur.left;
        }else if (cur == parent.left){
            parent.left = cur.left;
        }else {
            parent.right = cur.left;
        }
    }else {
        Node nextParent = cur;
        Node next = cur.right;
        while (next.left != null){
            nextParent = next;
            next = next.left;
        }

        cur.key = next.key;

        if (nextParent == cur){
            nextParent.right = next.right;
        }else {
            nextParent.left = next.right;
        }
    }
}

2.3 查找操作

public boolean find(int key){
    Node cur = root;
    while (cur != null){
        if (key == cur.key){
            return true;
        }else if (key < cur.key){
            cur = cur.left;
        }else {
            cur = cur.right;
        }
    }
    return false;
}

你可能感兴趣的:(数据结构,深度优先,算法)