• 删除节点没有左子树,直接返回右子树
    • 删除节点没有右子树,直接返回左子树
    • 两个都有,将删除节点的后继节点替换删除节点 ```java package com.alg.two;

    import com.alg.TreeNode;

    import java.util.Objects;

    /**

    • @author fuyao
    • @date 2022年06月02日 5:12 下午 */ public class DeleteTreeNode {

      public TreeNode deleteNode(TreeNode root, int key) {

      1. if (Objects.isNull(root)){
      2. return null;
      3. }
      4. if (root.val < key){
      5. root.left = deleteNode(root.right,key);
      6. return root;
      7. }
      8. if (root.val > key){
      9. root.left = deleteNode(root.left,key);
      10. return root;
      11. }
      12. if (root.val == key){
      13. if (Objects.isNull(root.left) && Objects.isNull(root.right)){
      14. return null;
      15. }
      16. if (Objects.isNull(root.left)){
      17. return root.right;
      18. }
      19. if (Objects.isNull(root.right)){
      20. return root.left;
      21. }
      22. TreeNode successor = root.right;
      23. while (Objects.nonNull(successor.left)){
      24. successor = successor.left;
      25. }
      26. root.right = deleteNode(successor.right,successor.val);
      27. successor.left = root.left;
      28. successor.right = root.right;
      29. return successor;
      30. }
      31. return root;

      }

    }

    ```