2021.11.21 - SX07-31.删除二叉搜索树中的节点

1. 题目

在这里插入图片描述
在这里插入图片描述

2. 思路

(1) 重建二叉搜索树

  • 先中序遍历二叉树,将所有值非key的结点加入队列中,然后依次从队列中弹出,重新构建单侧二叉树,即所有结点要么只有右子树,要么为叶子结点。
  • 可能不符合题意,但是测试可以通过。

(2) 模拟法

  • 利用递归删除结点,当根结点要被删除时,有两种情况:
    1. 根结点为叶子结点时,设置根结点为null并返回,使上一层结点的left或right指向null,实现删除;
    2. 根结点为非叶子结点时,要么从左子树中找到最大值,要么从右子树中找到最小值,覆盖当前根结点的值,然后对子树进行递归删除该值即可。

3. 代码

import java.util.LinkedList;
import java.util.Queue;

public class Test {
    
    
    public static void main(String[] args) {
    
    
    }
}

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 {
    
    
    private Queue<TreeNode> queue;

    public TreeNode deleteNode(TreeNode root, int key) {
    
    
        if (root == null) {
    
    
            return null;
        }
        queue = new LinkedList<>();
        inorder(root, key);
        if (queue.isEmpty()) {
    
    
            return null;
        }
        root = queue.poll();
        root.left = null;
        TreeNode cur = root;
        while (!queue.isEmpty()) {
    
    
            cur.right = queue.poll();
            cur = cur.right;
            cur.left = null;
        }
        cur.right = null;
        return root;
    }

    private void inorder(TreeNode root, int key) {
    
    
        if (root == null) {
    
    
            return;
        }
        inorder(root.left, key);
        if (root.val != key) {
    
    
            queue.offer(root);
        }
        inorder(root.right, key);
    }
}

class Solution1 {
    
    
    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 && root.right == null) {
    
    
                root = null;
            } else if (root.left != null) {
    
    
                TreeNode node = root.left;
                while (node.right != null) {
    
    
                    node = node.right;
                }
                root.val = node.val;
                root.left = deleteNode(root.left, node.val);
            } else {
    
    
                TreeNode node = root.right;
                while (node.left != null) {
    
    
                    node = node.left;
                }
                root.val = node.val;
                root.right = deleteNode(root.right, node.val);
            }
        }
        return root;
    }
}

Guess you like

Origin blog.csdn.net/qq_44021223/article/details/121460376