Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public static node removeNode(node n, int v)
- {
- if(n == null)
- {
- //then the node does not exist in the tree
- return null;
- }
- if(n.value == v)
- {
- //if it is a match, remove it.
- //now deal with its children.
- if(n.getChildren().size() == 0)
- {
- //there are no children.
- // we're done.
- return null;
- }
- else if(n.getChildren().size() == 1)
- {
- //there is only one child, who
- // by definition, has no children.
- return n.getChildren().get(0);
- }
- else
- {
- //there are two children
- //steal/promote child from tallest subtree
- if(n.left.height >= n.right.height)
- {
- //take rightmost child from leftmost side
- node oldLeft = n.left;
- node oldRight = n.right;
- int x = getLeftMostValue(n.right);
- node newNode = new node(x);
- newNode.left = oldLeft;
- if(oldRight.value != x)
- newNode.right = oldRight;
- return newNode;
- }
- else
- {
- //take leftmost child from rightmost side
- node oldLeft = n.left;
- node oldRight = n.right;
- int x = getLeftMostValue(n.right);
- node newNode = new node(x);
- if(oldLeft.value != x)
- newNode.left = oldLeft;
- newNode.right = oldRight;
- return newNode;
- }
- }
- }
- else if(n.value > v)
- {
- n.left = removeNode(n.left, v);
- display(root);
- assignHeight(n);
- if(n.left != null)
- rebalance(n.left);
- return n;
- }
- else if(n.value < v)
- {
- n.right = removeNode(n.right, v);
- display(root);
- assignHeight(n);
- if(n.right != null)
- rebalance(n.right);
- return n;
- }
- return null;
- }
Advertisement
Add Comment
Please, Sign In to add comment