图灵星球
课程目录 · 第 20 / 31 课
LeetCode题目讲解
  1. 1LeetCode刷题规划(精华题目列表)
  2. 219.Remove Nth Node From End of List删除链表的倒数第N个节点【LeetCode单题讲解系列】
  3. 326.Remove Duplicates from Sorted Array删除有序数组中的重复项【LeetCode单题讲解系列】
  4. 431. Next Permutation【LeetCode单题解析】
  5. 534.Find First and Last Position of Element in Sorted Array在排序数组中寻找元素的第一和最后一个位置【LeetCode单题讲解系列】
  6. 694. Binary Tree Inorder Traversal二叉树的中序遍历【LeetCode单题讲解系列】
  7. 7105. Construct Binary Tree from Preorder and Inorder Traversal【LeetCode单题解析】
  8. 8115. Distinct Subsequences【LeetCode单题解析】
  9. 9126. Word Ladder II【LeetCode单题解析】
  10. 10133. Clone Graph【LeetCode单题解析】
  11. 11144. Binary Tree Preorder Traversal 二叉树的前序遍历【单题解析系列】
  12. 12145. Binary Tree Postorder Traversal 二叉树的后序遍历【LeetCode单题讲解系列】
  13. 13206. Reverse Linked List反转链表【LeetCode单题讲解系列】
  14. 14225. Implement Stack using Queues用队列实现栈【单题解析系列】
  15. 15232. Implement Queue using Stacks用栈实现队列【单题解析系列】
  16. 16344.Reverse String反转字符串【LeetCode单题讲解系列】
  17. 17373. Find K Pairs with Smallest Sums查找和最小的k对数字【单题解析系列】
  18. 18378. Kth Smallest Element in a Sorted Matrix【LeetCode单题解析】
  19. 19399. Evaluate Division【单题解析系列】
  20. 20450. Delete Node in a BST【LeetCode单题解析】
  21. 21703.Kth Largest Element in a Stream数据流中的第K大元素【LeetCode单题讲解系列】
  22. 22704.Binary Search二分查找【LeetCode单题讲解系列】
  23. 23706. Design HashMap设计哈希映射【LeetCode单题讲解系列】
  24. 24739. Daily Temperatures 每日温度【LeetCode单题讲解系列】
  25. 25841.Keys and Rooms钥匙和房间【LeetCode单题讲解系列】
  26. 26875. Koko Eating Bananas科科吃香蕉【LeetCode单题解析】
  27. 27876.Middle of the Linked List 链表的中间结点【LeetCode单题讲解系列】
  28. 28994.Rotting Oranges 腐烂的橙子【LeetCode单题讲解系列】
  29. 291055. Shortest Way to Form String【LeetCode单题解析】
  30. 301123. Lowest Common Ancestor of Deepest Leaves【LeetCode单题解析】
  31. 31LeetCode题库过千,改如何规划刷题?【刷题规划系列】

450. Delete Node in a BST【LeetCode单题解析】

第 20 课 / 共 31 课Leetcode题目讲解

视频打不开?·在 YouTube 打开 ↗

题目: https://leetcode.com/problems/delete-node-in-a-bst/

class Solution {
    public TreeNode deleteNode(TreeNode root, int key) {
        if (root == null) {
            return null;
        } else if (root.val > key) {
            root.left = deleteNode(root.left, key);
            return root;
        } else if (root.val < key) {
            root.right = deleteNode(root.right, key);
            return root;
        }
        
        if (root.left == null || root.right == null) {
            return root.left == null ? root.right : root.left;
        } else if (root.right.left == null) {
            root.right.left = root.left;
            return root.right;
        }
        
        TreeNode prev = null, smallest = root.right;
        while (smallest.left != null) {
            prev = smallest;
            smallest = smallest.left;
        }
        
        prev.left = smallest.right;
        smallest.left = root.left;
        smallest.right = root.right;
        return smallest;
    }
}