美文网首页
LeetCode 第450题:删除二叉搜索树中的节点

LeetCode 第450题:删除二叉搜索树中的节点

作者: 放开那个BUG | 来源:发表于2020-08-17 19:30 被阅读0次

    1、前言

    题目描述

    2、思路

    首先,二叉搜索树因为其根节点大于左子树,小于右子树的性质,所以二叉搜索树的框架是:

    void BST(TreeNode root, int target) {
        if (root.val == target)
            // 找到目标,做点什么
        if (root.val < target) 
            BST(root.right, target);
        if (root.val > target)
            BST(root.left, target);
    }
    

    这道题主要是要考虑到找到节点后怎么删除(所谓的删除没有那么麻烦,不像链表的删除,需要找到前后节点,二叉树只需要把节点置为 null 即可)。如果找到的节点是叶子节点,那么非常方便,直接删除;如果节点有左子树或者右子树,那么删除此节点后,只需要把左子树或者右子树返回即可;如果此节点有左右子树,那么只需要找到此节点的右子树最小的节点,然后替换此节点即可。

    3、代码

    class Solution {
        public TreeNode deleteNode(TreeNode root, int key) {
            if(root == null){
                return null;
            }
            if(root.val == key){
                if(root.left == null && root.right == null){
                    return null;
                }else if(root.left != null && root.right == null){
                    return root.left;
                }else if(root.left == null && root.right != null){
                    return root.right;
                }else {
                    TreeNode node = getMin(root.right);
                    root.val = node.val;
                    root.right = deleteNode(root.right, node.val);
                }
            }else if(root.val > key){
                root.left = deleteNode(root.left, key);
            }else if(root.val < key){
                root.right = deleteNode(root.right, key);
            }
    
            return root;
        }
    
        private TreeNode getMin(TreeNode root){
            while(root.left != null){
                root = root.left;
            }
            return root;
        }
    }
    

    相关文章

      网友评论

          本文标题:LeetCode 第450题:删除二叉搜索树中的节点

          本文链接:https://www.haomeiwen.com/subject/wddorktx.html