zoukankan      html  css  js  c++  java
  • LeetCode450. 删除二叉搜索树中的节点

    ☆☆☆思路:二叉搜索树的删除操作是最难的。。。

    class Solution {
        public TreeNode deleteNode(TreeNode root, int key) {
            /**
             *  知识点:
             *    1. BST的递归模板
             *    2. BST删除某个节点,可以将其替换为左子树的最右节点 或者 右子树的最左节点
             *    3. 删除BST中最小的节点
             */
            if (root == null) return null;
            if (key < root.val) {
                // 待删除节点在左子树中
                root.left = deleteNode(root.left, key);
                return root;
            }else if (key > root.val) {
                // 待删除节点在右子树中
                root.right = deleteNode(root.right, key);
                return root;
            }else { // key = root.val,root 为待删除节点
                if (root.left == null) {
                    return root.right;
                }else if (root.right == null) {
                    return root.left;
                }else { // 左右子树都存在,返回后继节点(右子树最左叶子)作为新的根
                    TreeNode mostLeft = min(root.right);
                    // 以下两行顺序不能颠倒,否则会出现环路 "mostLeft.right = mostLeft"
                    mostLeft.right = deleteMin(root.right);
                    mostLeft.left = root.left;
                    return mostLeft;
                }
            }
        }
        private TreeNode min(TreeNode root) {
            if (root.left == null) {
                return root;
            }
            return min(root.left);
        }
        // 删除BST中最小的节点
        private TreeNode deleteMin(TreeNode root) {
            if (root.left == null) {
                return root.right;
            }
            root.left = deleteMin(root.left);
            return root;
        }
    }
  • 相关阅读:
    20201226 ZooKeeper
    20201220 分布式理论、架构设计(自定义RPC)
    20201217 Cluster模式潜在问题及解决方案、Web服务综合解决方案
    20201216 Nginx
    20201214 Tomcat
    20201209 Spring Boot
    20201206 Spring Data JPA
    20201205 Spring MVC
    20201128 IoC容器设计实现及Spring源码分析
    numpy数组及处理:效率对比
  • 原文地址:https://www.cnblogs.com/HuangYJ/p/14189498.html
Copyright © 2011-2022 走看看