teleias

removeNode AVL

Apr 6th, 2015
330
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.62 KB | None | 0 0
  1.     public static node removeNode(node n, int v)
  2.     {
  3.         if(n == null)
  4.         {
  5.             //then the node does not exist in the tree
  6.             return null;
  7.         }
  8.        
  9.         if(n.value == v)
  10.         {
  11.             //if it is a match, remove it.
  12.             //now deal with its children.
  13.             if(n.getChildren().size() == 0)
  14.             {
  15.                 //there are no children.
  16.                 // we're done.
  17.                 return null;
  18.             }
  19.             else if(n.getChildren().size() == 1)
  20.             {
  21.                 //there is only one child, who
  22.                 // by definition, has no children.
  23.                 return n.getChildren().get(0);
  24.             }
  25.             else
  26.             {
  27.                 //there are two children
  28.                 //steal/promote child from tallest subtree
  29.                 if(n.left.height >= n.right.height)
  30.                 {
  31.                     //take rightmost child from leftmost side
  32.                     node oldLeft = n.left;
  33.                     node oldRight = n.right;
  34.                     int x = getLeftMostValue(n.right);
  35.                     node newNode = new node(x);
  36.                     newNode.left = oldLeft;
  37.                     if(oldRight.value != x)
  38.                         newNode.right = oldRight;
  39.                     return newNode;
  40.                 }
  41.                 else
  42.                 {
  43.                     //take leftmost child from rightmost side
  44.                     node oldLeft = n.left;
  45.                     node oldRight = n.right;
  46.                     int x = getLeftMostValue(n.right);
  47.                     node newNode = new node(x);
  48.                     if(oldLeft.value != x)
  49.                         newNode.left = oldLeft;
  50.                     newNode.right = oldRight;
  51.                     return newNode;
  52.                 }
  53.             }
  54.         }
  55.         else if(n.value > v)
  56.         {
  57.             n.left = removeNode(n.left, v);
  58.             display(root);
  59.             assignHeight(n);
  60.             if(n.left != null)
  61.                 rebalance(n.left);
  62.             return n;
  63.         }
  64.         else if(n.value < v)
  65.         {
  66.             n.right = removeNode(n.right, v);
  67.             display(root);
  68.             assignHeight(n);
  69.             if(n.right != null)
  70.                 rebalance(n.right);
  71.             return n;
  72.         }
  73.         return null;
  74.     }
Advertisement
Add Comment
Please, Sign In to add comment