当前位置: 首页 > article >正文

Java | Leetcode Java题解之第450题删除二叉搜索树中的节点

题目:

题解:

class Solution {
    public TreeNode deleteNode(TreeNode root, int key) {
        TreeNode cur = root, curParent = null;
        while (cur != null && cur.val != key) {
            curParent = cur;
            if (cur.val > key) {
                cur = cur.left;
            } else {
                cur = cur.right;
            }
        }
        if (cur == null) {
            return root;
        }
        if (cur.left == null && cur.right == null) {
            cur = null;
        } else if (cur.right == null) {
            cur = cur.left;
        } else if (cur.left == null) {
            cur = cur.right;
        } else {
            TreeNode successor = cur.right, successorParent = cur;
            while (successor.left != null) {
                successorParent = successor;
                successor = successor.left;
            }
            if (successorParent.val == cur.val) {
                successorParent.right = successor.right;
            } else {
                successorParent.left = successor.right;
            }
            successor.right = cur.right;
            successor.left = cur.left;
            cur = successor;
        }
        if (curParent == null) {
            return cur;
        } else {
            if (curParent.left != null && curParent.left.val == key) {
                curParent.left = cur;
            } else {
                curParent.right = cur;
            }
            return root;
        }
    }
}

http://www.kler.cn/news/328527.html

相关文章:

  • Arduino UNO R3自学笔记7 之 Arduino使用PWM电机调速
  • 服务器数据恢复—存储映射到服务器上的卷无法挂载的数据恢复案例
  • DC00025【含论文】基于协同过滤推荐算法springboot视频推荐管理系统
  • 使用Yasboot安装YashanDB的疑惑和建议
  • 进阶数据库系列(十三):PostgreSQL 分区分表
  • SolidWorks机器转ROS2 URDF
  • Linux下send函数和recv函数
  • AWS Redshift把老用户权限赋予新用户
  • 201 Created
  • 如何在Windows、Mac和Linux系统上安装和更新Stable Diffusion WebUI
  • Spark SQL分析层优化
  • 中国电信解锁万亿参数大模型:TeleAI的创新与突破
  • Docker镜像命令和容器命令
  • 《征服数据结构》哈夫曼树(Huffman Tree)
  • Python 封装 socket 为 [TCP/UDP/MULTICAST] 服务端
  • 计算机毕业设计 服装生产信息管理系统的设计与实现 Java实战项目 附源码+文档+视频讲解
  • Datawhale Leecode基础算法篇 task04:贪心算法
  • SpringBoot 使用自定义注解和枚举类对接口入参校验
  • 2024年寒假开学赛题解
  • Python空间地表联动贝叶斯地震风险计算模型
  • 【SpringCloud】优雅实现远程调⽤-OpenFeign
  • python 实现rayleigh quotient瑞利商算法
  • 数据结构-4.3.串的存储结构
  • 深入理解网络通信: 长连接、短连接与WebSocket
  • Spring系列 AOP实现过程
  • 【PostgreSQL】入门篇——PostgreSQL 的历史、特点和优势
  • 开卷可扩展自动驾驶(OpenDriveLab)
  • express,MySQL 实现登录接口,如果用户未注册直接注册
  • 【Python】Uvicorn:Python 异步 ASGI 服务器详解
  • vue3 环境配置vue-i8n国际化