Guest User

Untitled

a guest
Jan 6th, 2025
151
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.94 KB | None | 0 0
  1. function remove(data, node, parent):
  2.     if node is null:
  3.         return null  // Base case: data not found
  4.  
  5.     // Traverse the tree
  6.     if data < node.data:
  7.         // Move to the left child
  8.         node.left = remove(data, node.left, node)
  9.     else if data > node.data:
  10.         // Move to the right child
  11.         node.right = remove(data, node.right, node)
  12.     else:
  13.         // Node found
  14.         if node.left is null and node.right is null:
  15.             // Case 1: No children (leaf node)
  16.             if parent is null:
  17.                 return null  // Tree becomes empty
  18.             if parent.left == node:
  19.                 parent.left = null  // Remove reference from parent
  20.             else:
  21.                 parent.right = null  // Remove reference from parent
  22.         else if node.left is null:
  23.             // Case 2: One child (right)
  24.             if parent is null:
  25.                 return node.right  // Update root
  26.             if parent.left == node:
  27.                 parent.left = node.right  // Replace with right child
  28.             else:
  29.                 parent.right = node.right  // Replace with right child
  30.         else if node.right is null:
  31.             // Case 2: One child (left)
  32.             if parent is null:
  33.                 return node.left  // Update root
  34.             if parent.left == node:
  35.                 parent.left = node.left  // Replace with left child
  36.             else:
  37.                 parent.right = node.left  // Replace with left child
  38.         else:
  39.             // Case 3: Two children
  40.             predecessor = findMax(node.left)  // Find the predecessor
  41.             node.data = predecessor.data  // Copy predecessor's value to node
  42.             node.left = remove(predecessor.data, node.left, node)  // Remove predecessor
  43.  
  44.     return node  // Return the updated node
  45.  
  46. function findMax(node):
  47.     while node.right is not null:
  48.         node = node.right
  49.     return node  // Return the node with the maximum value
Advertisement
Add Comment
Please, Sign In to add comment