450. Delete Node in a BST**

本文介绍了一种在二叉搜索树(BST)中删除指定键值节点的方法,通过递归方式实现,避免了额外记录父节点的复杂性。并提供了具体的代码实现及两个有效的示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Given a root node reference of a BST and a key, delete the node with the given key in the BST. Return the root node reference (possibly updated) of the BST.

Basically, the deletion can be divided into two stages:

  1. Search for a node to remove.
  2. If the node is found, delete the node.

Note: Time complexity should be O(height of tree).

Example:

root = [5,3,6,2,4,null,7]
key = 3

    5
   / \
  3   6
 / \   \
2   4   7

Given key to delete is 3. So we find the node with value 3 and delete it.

One valid answer is [5,4,6,2,null,null,7], shown in the following BST.

    5
   / \
  4   6
 /     \
2       7

Another valid answer is [5,2,6,null,4,null,7].

    5
   / \
  2   6
   \   \
    4   7
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public TreeNode deleteNode(TreeNode root, int key) {
        if(root==null) return null;
        if(key<root.val) root.left=deleteNode(root.left, key);
        else if(key>root.val) root.right = deleteNode(root.right, key);
        else{
            if(root.left==null) return root.right;
            else if(root.right ==null) return root.left;
            else{
                TreeNode min = findmin(root.right);
                root.val = min.val;
                root.right = deleteNode(root.right, min.val);
            }
        }
        return root;
    }
    private TreeNode findmin(TreeNode root){
        if(root==null) return null;
        while(root.left!=null){
            root=root.left;
        }
        return root;
    }
}
总结:这种用递归的方法比较方便。否则还要记录父节点是什么。
内容概要:本文详细介绍了C语言指针和字符串操作的基础知识与高级技巧。指针部分涵盖了指针作为数据类型的特点,包括指针变量的定义、间接赋值的应用场景及其重要性,以及不同级别的指针如何在函数间传递并修改实参的值。同时强调了指针操作的安全性问题,如不允许向NULL或未知地址拷贝内存,并讲解了`void*`指针的作用及其转换规则。字符串操作部分则重点讨论了字符串初始化、`sizeof`与`strlen`的区别、字符`\0`的作用及其与其他符号的区别,还展示了数组法和指针法两种操作字符串的方式,并给出了几个常见的字符串处理算法实例,如统计子串出现次数、去除字符串两端空白字符等。 适用人群:具有初步C语言基础的学习者,特别是对指针和字符串操作有进一步需求的编程人员。 使用场景及目标:①帮助读者深入理解指针的工作机制,掌握通过指针间接访问和修改内存的技术;②使读者能够熟练运用字符串操作的基本函数,并能编写高效的字符串处理代码;③培养读者的安全意识,避免因不当使用指针而导致程序崩溃或产生未定义行为。 阅读建议:由于指针和字符串是C语言中较为复杂的概念,建议读者在学习过程中多做笔记,动手实践书中的示例代码,尤其要注意理解指针间接赋值的原理,以及字符串处理函数的具体实现细节。此外,对于`void*`指针的理解和使用,应特别留意其类型转换的要求,确保代码的安全性和正确性。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值