Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public boolean delete(Node node, Delegate d){
- Node current = root;
- Node parent = root;
- boolean leftChild = false;
- while(current.delegate != delegate){
- parent = current;
- if(d < current.d){
- // Move to the left if searched value is less
- current = current.left;
- leftChild = true;
- }
- else{
- // Move to the right if searched value is >=
- current = current.right;
- leftChild = false;
- }
- if(current == null){
- return false;
- }
- }
- // if reached here means node to be deleted is found
- // Leaf node deletion case
- if(current.left == null && current.right == null){
- System.out.println("Leaf node deletion case");
- // if root node is to be deleted
- if(current == root){
- root = null;
- }
- // left child
- else if(leftChild){
- parent.left = null;
- }
- // right child
- else{
- parent.right = null;
- }
- }
- // Node to be deleted has one child case
- // Node to be deleted has right child
- else if(current.left == null){
- System.out.println("One right child deletion case");
- // if root node is to be deleted
- if(current == root){
- root = current.right;
- }
- // if deleted node is left child
- else if(leftChild){
- parent.left = current.right;
- }
- // if deleted node is right child
- else{
- parent.right = current.right;
- }
- }
- // Node to be deleted has left child
- else if(current.right == null){
- System.out.println("One left child deletion case");
- if(current == root){
- root = current.left;
- }
- // if deleted node is left child
- else if(leftChild){
- parent.left = current.left;
- }
- // if deleted node is right child
- else{
- parent.right = current.left;
- }
- }
- // Node to be deleted has two children case
- else{
- System.out.println("Two children deletion case");
- // find in-order heir of the node to be deleted
- Node heir = findHeir(current);
- if(current == root){
- root = heir;
- }
- // if deleted node is left child
- else if(leftChild){
- parent.left = heir;
- }
- // if deleted node is right child
- else{
- parent.right = heir;
- }
- heir.left = current.left;
- }
- return true;
- }
- // Method to find the in-order heir of the deleted node
- private Node findHeir(Node node){
- Node successor = node;
- Node successorParent = node;
- // Start from the right child of the node to be deleted
- Node current = node.right;
- while(current != null){
- successorParent = successor;
- successor = current;
- current = current.left;
- }
- // When In-order heir is in the left subtree
- // perform two ref changes here as we have
- // access to successorParent
- if(successor != node.right){
- successorParent.left = successor.right;
- // applicable only when heir is not right child
- // so doing here
- successor.right = node.right;
- }
- return successor;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement