c#数据结构之二叉搜索树(BST)

本文详细介绍了二叉搜索树(BST)的特点,包括节点的键值关系以及中序遍历的性质。同时,展示了BST中查找、插入和删除操作的递归实现,包括找到目标节点、新增节点以及删除指定节点的逻辑流程。这些基本操作对于理解BST的数据结构和算法至关重要。
摘要由CSDN通过智能技术生成

特点

  • 节点的左子树仅包含键小于节点键的节点。
  • 节点的右子树仅包含键大于节点键的节点。
  • 左右子树也必须是二叉搜索树。

事实

  • BST 的中序遍历总是产生排序的输出。
  • 通过对唯一给定的遍历进行排序来获得中序遍历。

查找

public Node search(Node root,
                   int key)
{
    if (root == null ||
        root.key == key)
        return root;
 
    if (root.key < key)
       return search(root.right, key);
 
    return search(root.left, key);
}

插入

 Node insertRec(Node root, int key)
{
    if (root == null) {
        root = new Node(key);
        return root;
    }

    if (key < root.key)
        root.left = insertRec(root.left, key);
    else if (key > root.key)
        root.right = insertRec(root.right, key);

    return root;
}

删除

Node deleteRec(Node root, int key)
{
    if (root == null)
        return root;

    if (key < root.key)
        root.left = deleteRec(root.left, key);
    else if (key > root.key)
        root.right = deleteRec(root.right, key);
    else {
        if (root.left == null)
            return root.right;
        else if (root.right == null)
            return root.left;

        root.key = minValue(root.right);

        root.right = deleteRec(root.right, root.key);
    }
    return root;
}

int minValue(Node root)
{
    int minv = root.key;
    while (root.left != null) {
        minv = root.left.key;
        root = root.left;
    }
    return minv;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值