BinaryTreeDelete.java 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. import java.util.LinkedList;
  2. import java.util.Queue;
  3. class Node {
  4. int data;
  5. Node left, right;
  6. Node(int d) {
  7. data = d;
  8. left = right = null;
  9. }
  10. }
  11. class BinaryTreeDelete {
  12. // Function to delete a node from the binary tree
  13. static Node deleteNode(Node root, int val) {
  14. if (root == null) return null;
  15. // Use a queue to perform BFS
  16. Queue<Node> q = new LinkedList<>();
  17. q.add(root);
  18. Node target = null;
  19. // Find the target node
  20. while (!q.isEmpty()) {
  21. Node curr = q.poll();
  22. if (curr.data == val) {
  23. target = curr;
  24. break;
  25. }
  26. if (curr.left != null) q.add(curr.left);
  27. if (curr.right != null) q.add(curr.right);
  28. }
  29. if (target == null) return root;
  30. // Find the deepest rightmost node and its parent
  31. Node lastNode = null;
  32. Node lastParent = null;
  33. Queue<Node> q1 = new LinkedList<>();
  34. Queue<Node> parentQueue = new LinkedList<>();
  35. q1.add(root);
  36. parentQueue.add(null);
  37. while (!q1.isEmpty()) {
  38. Node curr = q1.poll();
  39. Node parent = parentQueue.poll();
  40. lastNode = curr;
  41. lastParent = parent;
  42. if (curr.left != null) {
  43. q1.add(curr.left);
  44. parentQueue.add(curr);
  45. }
  46. if (curr.right != null) {
  47. q1.add(curr.right);
  48. parentQueue.add(curr);
  49. }
  50. }
  51. // Replace target's value with the last node's value
  52. target.data = lastNode.data;
  53. // Remove the last node
  54. if (lastParent != null) {
  55. if (lastParent.left == lastNode) lastParent.left = null;
  56. else lastParent.right = null;
  57. } else {
  58. return null;
  59. }
  60. return root;
  61. }
  62. // In-order traversal
  63. static void inorder(Node root) {
  64. if (root == null) return;
  65. inorder(root.left);
  66. System.out.print(root.data + " ");
  67. inorder(root.right);
  68. }
  69. public static void main(String[] args) {
  70. Node root = new Node(2);
  71. root.left = new Node(3);
  72. root.right = new Node(4);
  73. root.left.left = new Node(5);
  74. root.left.right = new Node(6);
  75. System.out.print("Original tree (in-order): ");
  76. inorder(root);
  77. System.out.println();
  78. int valToDel = 3;
  79. root = deleteNode(root, valToDel);
  80. System.out.print("Tree after deleting " + valToDel + " (in-order): ");
  81. inorder(root);
  82. System.out.println();
  83. }
  84. }