leetcode450. 删除二叉搜索树中的节点(java详解版)

一:题目

在这里插入图片描述

二:上码

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    /**
        递归:
        1.确定递归参数和返回值
            返回值的话 我们这里最终返回的还是TreeNode 因为这里要的还是二叉树。
        2.确定递归的终止条件
            遍历到所有结点都没找到  返回 null    
        3.递归体当中可以分为5种情况
            1>:未找到key 那么的话我们就返回null 
            2>:找到了key 但是root.left == null 那么右子树顶替直接返回root.right
            3>:找到了key 但是root.right == null 那么右子树顶替直接返回root.left
            4>:找到了key 但是左右子树都为空 那么的话 直接删除
            5>:找到了key 但是左右子树都不为空 那么的话 我们是root.ringt顶上去,然后将root.left放到
                root.left子树中最左下的一个结点旁边,因为root.right中所有的结点是比root.left中的结点
                的值大的,那么的话我们我们就需要将root.left子树放到root.right子树中最小的一个结点下面 
     */
    public TreeNode deleteNode(TreeNode root, int key) {
        if (root == null) return null;

        if (root.val > key) root.left = deleteNode(root.left,key);
        else if (root.val < key) root.right = deleteNode(root.right,key);
        else {
                 System.out.println("wyj");
                if (root.left == null && root.right == null) {
                    root = null;
                    return root;
                } else if (root.left != null && root.right == null) {
                    root = root.left;
                    return  root; 
                } else if (root.right != null && root.left == null) {
                    root = root.right;
                    return root;
                } else {
                    TreeNode temp = root.right;
                    while (temp.left != null) {
                        temp = temp.left;
                    }
                    temp.left = root.left;
                    root = root.right;
                    
                    System.out.println("wyj");
                    return root;


                }
        }
//  System.out.println("wyj");
        return root;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

天天向上的菜鸡杰!!

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值