5.6: Example extract of Java code for binary tree delete operation
selected template will load here
This action is not available.
private Treap1<K, V>.TreapNode deleteNode(K k, Treap1<K, V>.TreapNode node, Deleted del) { if (node == null) { return null; } else if (k.compareTo(node.k) < 0) { node.left = (k, node.left, del) ; } else if (k.compareTo(node.k) > 0) { node.right = deleteNode(k, node.right, del); // k.compareTo(node.k) == 0 } else if ( node.left == null ) { del.success = true; return node.right; } else if ( node.right == null) { del.success = true; return node.left; } else if (node.left !=null && node.right != null){ /* // non-standard method, // left rotate and all delete on left subtree TreapNode tmp = node.right; node.right = node.right.left; tmp.left = node; node = tmp; node.left = deleteNode(k , node.left, del); */ // more standard method ? doesn't disturb tree structure as much // find leftmost descendant of the right child node and replace contents TreapNode n2 = node.right; TreapNode previous2 = null; while (n2.left != null) { previous2 = n2; n2 = n2.left; } if (previous2 != null) { previous2.left = n2.right; //n2 has no parent link, orphaned } else { node.right = n2.right; //n2 has no parent link, orphaned } node.k = n2.k; node.val = n2.val; del.success = true; // once n2 out of scope, the orphaned node at n2 will be garbage collected, } return node; }