450. 删除二叉搜索树中的节点

image.png
image.png
image.png

迭代

  1. /**
  2. * Definition for a binary tree node.
  3. * public class TreeNode {
  4. * int val;
  5. * TreeNode left;
  6. * TreeNode right;
  7. * TreeNode(int x) { val = x; }
  8. * }
  9. */
  10. class Solution {
  11. public TreeNode deleteNode(TreeNode root, int key) {
  12. if (root == null) return null;
  13. if (root.val < key) {
  14. root.right = deleteNode(root.right, key);
  15. } else if (root.val > key) {
  16. root.left = deleteNode(root.left, key);
  17. } else {
  18. //找到了要删除的节点
  19. //如果左子树为空,返回右子树
  20. if (root.left == null)
  21. return root.right;
  22. if (root.right == null)
  23. return root.left;
  24. //说明两个子节点都不为空,我们可以找左子树的最大值,
  25. //也可以找右子树的最小值替换
  26. //这里是用右子树的最小值替换
  27. TreeNode minNode = root.right;
  28. while(minNode.left != null ) {
  29. minNode = minNode.left;
  30. }
  31. root.val = minNode.val;
  32. root.right = deleteNode(root.right, root.val);
  33. }
  34. return root;
  35. }
  36. }