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

浅浅的花香味﹌ 2023-10-04 09:11 117阅读 0赞

给定一个二叉搜索树的根节点 root 和一个值 key,删除二叉搜索树中的 key 对应的节点,并保证二叉搜索树的性质不变。返回二叉搜索树(有可能被更新)的根节点的引用。

一般来说,删除节点可分为两个步骤:

  1. 首先找到需要删除的节点;
  2. 如果找到了,删除它。

说明: 要求算法时间复杂度为 O(h),h 为树的高度。

示例:

  1. root = [5,3,6,2,4,null,7]
  2. key = 3
  3. 5
  4. / \
  5. 3 6
  6. / \ \
  7. 2 4 7
  8. 给定需要删除的节点值是 3,所以我们首先找到 3 这个节点,然后删除它。
  9. 一个正确的答案是 [5,4,6,2,null,null,7], 如下图所示。
  10. 5
  11. / \
  12. 4 6
  13. / \
  14. 2 7
  15. 另一个正确答案是 [5,2,6,null,4,null,7]。
  16. 5
  17. / \
  18. 2 6
  19. \ \
  20. 4 7
  21. package Solution450;
  22. public class TreeNode {
  23. int val;
  24. TreeNode left;
  25. TreeNode right;
  26. TreeNode() {
  27. }
  28. TreeNode(int val) {
  29. this.val = val;
  30. }
  31. TreeNode(int val, TreeNode left, TreeNode right) {
  32. this.val = val;
  33. this.left = left;
  34. this.right = right;
  35. }
  36. }
  37. package Solution450;
  38. class Solution {
  39. public TreeNode deleteNode(TreeNode root, int key) {
  40. // Return if the tree is empty
  41. if (root == null)
  42. return root;
  43. // Find the node to be deleted
  44. if (key < root.val)
  45. root.left = deleteNode(root.left, key);
  46. else if (key > root.val)
  47. root.right = deleteNode(root.right, key);
  48. else {
  49. // If the node is with only one child or no child
  50. if (root.left == null)
  51. return root.right;
  52. else if (root.right == null)
  53. return root.left;
  54. // If the node has two children
  55. // Place the inorder successor in position of the node to be deleted
  56. root.val = minValue(root.right);
  57. // Delete the inorder successor
  58. root.right = deleteNode(root.right, root.val);
  59. }
  60. return root;
  61. }
  62. // Find the inorder successor
  63. int minValue(TreeNode root) {
  64. int minv = root.val;
  65. while (root.left != null) {
  66. minv = root.left.val;
  67. root = root.left;
  68. }
  69. return minv;
  70. }
  71. void inOrder(TreeNode root) {
  72. if (root != null) {
  73. inOrder(root.left);
  74. System.out.println(root.val);
  75. inOrder(root.right);
  76. }
  77. }
  78. public static void main(String[] args) {
  79. Solution sol = new Solution();
  80. TreeNode first = new TreeNode(4);
  81. first.left = new TreeNode(2);
  82. first.right = new TreeNode(7);
  83. first.left.left = new TreeNode(1);
  84. first.left.right = new TreeNode(3);
  85. sol.inOrder(first);
  86. System.out.println(sol.deleteNode(first, 2));
  87. sol.inOrder(first);
  88. }
  89. }

发表评论

表情:
评论列表 (有 0 条评论,117人围观)

还没有评论,来说两句吧...

相关阅读