6.6: Example extract of Java code for binary tree delete operation
- Page ID
- 46730
\( \newcommand{\vecs}[1]{\overset { \scriptstyle \rightharpoonup} {\mathbf{#1}} } \) \( \newcommand{\vecd}[1]{\overset{-\!-\!\rightharpoonup}{\vphantom{a}\smash {#1}}} \)\(\newcommand{\id}{\mathrm{id}}\) \( \newcommand{\Span}{\mathrm{span}}\) \( \newcommand{\kernel}{\mathrm{null}\,}\) \( \newcommand{\range}{\mathrm{range}\,}\) \( \newcommand{\RealPart}{\mathrm{Re}}\) \( \newcommand{\ImaginaryPart}{\mathrm{Im}}\) \( \newcommand{\Argument}{\mathrm{Arg}}\) \( \newcommand{\norm}[1]{\| #1 \|}\) \( \newcommand{\inner}[2]{\langle #1, #2 \rangle}\) \( \newcommand{\Span}{\mathrm{span}}\) \(\newcommand{\id}{\mathrm{id}}\) \( \newcommand{\Span}{\mathrm{span}}\) \( \newcommand{\kernel}{\mathrm{null}\,}\) \( \newcommand{\range}{\mathrm{range}\,}\) \( \newcommand{\RealPart}{\mathrm{Re}}\) \( \newcommand{\ImaginaryPart}{\mathrm{Im}}\) \( \newcommand{\Argument}{\mathrm{Arg}}\) \( \newcommand{\norm}[1]{\| #1 \|}\) \( \newcommand{\inner}[2]{\langle #1, #2 \rangle}\) \( \newcommand{\Span}{\mathrm{span}}\)\(\newcommand{\AA}{\unicode[.8,0]{x212B}}\)
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; }