当前位置:首页 > 随笔 > 正文内容

二叉搜索树操作:查找最近公共祖先、节点插入与删除

访客 随笔 2026年8月6日 1

寻找二叉搜索树的最近公共祖先

问题描述:

以下代码实现包含了第二种情况(节点自身作为公共祖先)的解决方案。

递归解法:

class BSTAncestorFinder {
    public TreeNode findCommonAncestor(TreeNode treeRoot, TreeNode node1, TreeNode node2) {
        if (treeRoot == null) {
            return null;
        }
        if (treeRoot.value > node1.value && treeRoot.value > node2.value) {
            return findCommonAncestor(treeRoot.leftChild, node1, node2);
        }
        if (treeRoot.value < node1.value && treeRoot.value < node2.value) {
            return findCommonAncestor(treeRoot.rightChild, node1, node2);
        }
        return treeRoot;
    }
}

迭代解法:

class BSTAncestorFinder {
    public TreeNode findCommonAncestor(TreeNode treeRoot, TreeNode node1, TreeNode node2) {
        while (treeRoot != null) {
            if (treeRoot.value > node1.value && treeRoot.value > node2.value) {
                treeRoot = treeRoot.leftChild;
            } else if (treeRoot.value < node1.value && treeRoot.value < node2.value) {
                treeRoot = treeRoot.rightChild;
            } else {
                return treeRoot;
            }
        }
        return treeRoot;
    }
}

在二叉搜索树中插入新节点

问题描述:

关键点: 存在多种可能的插入位置,我们只需实现一种即可。最简单的方式是将新节点插入为叶子节点。这意味着插入操作总是发生在树的底部。

class BSTInserter {
    public TreeNode insertNode(TreeNode treeRoot, int newValue) {
        if (treeRoot == null) {
            return new TreeNode(newValue);
        }
        if (treeRoot.value > newValue) {
            treeRoot.leftChild = insertNode(treeRoot.leftChild, newValue);
        } else if (treeRoot.value < newValue) {
            treeRoot.rightChild = insertNode(treeRoot.rightChild, newValue);
        }
        return treeRoot;
    }
}

从二叉搜索树中删除节点

问题描述:

此问题有一定难度,需要考虑多种情况

五种情况分析:

  1. 未找到要删除的节点
  2. 要删除的节点是叶子节点(左右子节点都为空)
  3. 左子节点非空,右子节点为空
  4. 左子节点为空,右子节点非空
  5. 左右子节点都不为空。采用右子树继承策略,需要将左子树移至右子树的最左节点(即比被删除节点值稍大的节点)
class BSTNodeRemover {
    public TreeNode removeNode(TreeNode treeRoot, int keyValue) {
        if (treeRoot == null) {
            return null;
        }

        // 终止条件
        if (treeRoot.value == keyValue) {
            if (treeRoot.leftChild == null && treeRoot.rightChild == null) {
                return null;
            } else if (treeRoot.leftChild != null && treeRoot.rightChild == null) {
                return treeRoot.leftChild;
            } else if (treeRoot.leftChild == null && treeRoot.rightChild != null) {
                return treeRoot.rightChild;
            } else {
                // 选择右子树继承
                TreeNode current = treeRoot.rightChild;
                while (current.leftChild != null) {
                    current = current.leftChild;
                }
                current.leftChild = treeRoot.leftChild; // 将左子树移至右子树最左节点的左侧
                return treeRoot.rightChild;
            }
        }

        // 递归逻辑。到这里说明 treeRoot.value != keyValue
        if (treeRoot.value > keyValue) {
            treeRoot.leftChild = removeNode(treeRoot.leftChild, keyValue);
        } else {
            treeRoot.rightChild = removeNode(treeRoot.rightChild, keyValue);
        }
        return treeRoot;
    }
}

总结

二叉搜索树的相关问题,通常使用迭代方法更为简便。(由于 BST 的有序特性,迭代解法不需要使用栈结构)

相关文章

可以按小时收费的VPS

很多 VPS 提供商都支持 按小时计费(hourly billing),想短期试用 / 临时搭建节点、测试网络、短期项目等场景非常合适。下面是当前最主流且靠谱的按小时 VPS 选项,分别按不同需求场景整理: 1. Vultr(全球节点,包括日本) 按小时计费 可选机房:东京 / 大阪 / 洛杉矶 / 法兰克福 / 伦敦 … 支持 PayPal(部分情况),但更常用信用卡/PayPal+卡价格参考$...

在 iPhone 上下载国外App

地区/国家限制App Store 会根据 Apple ID 的国家或地区限制应用下载。如果你的 Apple ID 绑定的是中国大陆,就可能无法下载 OpenAI 官方的 ChatGPT 应用,因为它在大陆 App Store 不上架。解决办法:换成美国、加拿大、香港等地区的 Apple ID。或者在现有 Apple ID 上更改地区。注册一个国外 Apple ID(推荐)比如注册 美国区 Appl...

Node.js 中的异步编程:回调与 Promise

Node.js 是一个基于 JavaScript 构建的单线程、非阻塞运行环境,它通过异步编程机制来高效处理多个操作。在执行如文件读取、API 请求或数据库查询等任务时,Node.js 不会等待这些操作完成,而是使用回调函数和 Promise 来避免阻塞主线程。 回调方式实现异步 那么当异步操作完成后,Node.js 如何知道接下来要做什么呢?这就要用到 回调函数(callback)。 回调本质上...

Selenium自动化测试入门指南

Selenium自动化测试入门指南

什么是自动化测试? 自动化测试是指利用软件工具自动执行测试用例,模拟用户操作,如打开网页、点击链接、输入文本等,并验证结果是否符合预期。 其主要优点包括: 大幅减少人工成本 测试速度快 可以在非工作时间运行 支持持续集成和交付 然而,它也存在一些局限性,例如开发成本较高、不适合快速变化的项目、依赖稳定的UI界面等。 自动化测试的应用条件 适合引入自动化测试的情况包括: 手动测试耗时且需要大量...

MariaDB Galera集群故障快速恢复指南

OpenStack控制节点采用三节点MariaDB Galera集群架构。当数据库集群因故障重启时,有时会出现Galera集群无法正常启动的问题。虽然有多种方法可以恢复数据库服务,但如何实现快速启动同时确保数据完整性呢? 通过分析日志发现,MariaDB Galera集群节点宕机时会在日志中输出以下信息: [Note] WSREP: 新集群视图:全局状态: 874d8e7e-5980-11e8-8...

Android 中 EventBus 的通信机制与实现原理深度解析

EventBus 核心设计思想 EventBus 是一个基于观察者模式的事件总线框架,广泛应用于 Android 平台以实现组件解耦。它通过中心化的消息分发机制,使不同层级、不同线程的对象能够以"发布-订阅"方式通信,避免了传统接口回调或广播带来的强依赖问题。 核心角色说明 事件(Event):任意 Java 对象,作为数据载体,如网络状态变更通知、用户登录信息等。 发布者(Publi...

发表评论

访客

◎欢迎参与讨论,请在这里发表您的看法和观点。