1. /**
    2. * Definition for a binary tree node.
    3. * public class TreeNode {
    4. * int val;
    5. * TreeNode left;
    6. * TreeNode right;
    7. * TreeNode() {}
    8. * TreeNode(int val) { this.val = val; }
    9. * TreeNode(int val, TreeNode left, TreeNode right) {
    10. * this.val = val;
    11. * this.left = left;
    12. * this.right = right;
    13. * }
    14. * }
    15. */
    16. class Solution {
    17. public TreeNode deleteNode(TreeNode root, int key) {
    18. //找不到了,忽略不用管
    19. if(root == null){
    20. return null;
    21. }
    22. //2找到了,就删除这个节点
    23. if(root.val == key){
    24. //2.1如果只有左子树or只有右子树,那么就返回另一个字数就好了
    25. // 这样相当于把root的紫薯返回个root的上级,就相当于删除了root
    26. if(root.left == null){
    27. return root.right;
    28. }
    29. if(root.right == null){
    30. return root.left;
    31. }
    32. //2.2 如果左右子数都有,就需要找后继
    33. //后继就是,root的right 然后 再一路向左。也就是比root大的全部结点里最小的一个
    34. TreeNode next = root.right;
    35. //一路向左
    36. while (next.left != null) {
    37. next = next.left;
    38. }
    39. //2.3 然后把后继删除,root的位置,使用后继替换,也就是用后继替换root
    40. root.right = deleteNode(root.right,next.val);
    41. root.val = next.val;
    42. return root;
    43. }
    44. //检索,如果当前结点比key小,就去右子树检索。否则就去左子树检索
    45. if(root.val < key){
    46. root.right = deleteNode(root.right,key);
    47. }else {
    48. root.left = deleteNode(root.left, key);
    49. }
    50. return root;
    51. }
    52. }