19.09.2015 Views

Prentice.Hall.Introduction.to.Java.Programming,.Brief.Version.9th.(2014).[sharethefiles.com]

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

<br />

<br />

<br />

<br />

<br />

<br />

<br />

<br />

<br />

<br />

<br />

public boolean insert(E e) {<br />

boolean successful = super.insert(e);<br />

if (!successful)<br />

return false; // e is already in the tree<br />

else {<br />

ensureRBTree(e);<br />

}<br />

}<br />

return true; // e is inserted<br />

/** Ensure that the tree is a red-black tree */<br />

private void ensureRBTree(E e) {<br />

Get the path that leads <strong>to</strong> element e from the root.<br />

int i = path.size() – 1; // Index <strong>to</strong> the current node in the path<br />

Get u, v from the path. u is the node that contains e and v<br />

is the parent of u.<br />

Color u red;<br />

}<br />

if (u == root) // If e is inserted as the root, set root black<br />

u.setBlack();<br />

else if (v.isRed())<br />

fixDoubleRed(u, v, path, i); // Fix double-red violation at u<br />

/** Fix double-red violation at node u */<br />

private void fixDoubleRed(RBTreeNode u, RBTreeNode v,<br />

ArrayList path, int i) {<br />

Get w from the path. w is the grandparent of u.<br />

// Get v's sibling named x<br />

RBTreeNode x = (w.left == v) ?<br />

(RBTreeNode)(w.right) : (RBTreeNode)(w.left);<br />

if (x == null || x.isBlack()) {<br />

// Case 1: v's sibling x is black<br />

if (w.left == v && v.left == u) {<br />

// Case 1.1: u < v < w, Restructure and recolor nodes<br />

}<br />

else if (w.left == v && v.right == u) {<br />

// Case 1.2: v < u < w, Restructure and recolor nodes<br />

}<br />

else if (w.right == v && v.right == u) {<br />

9

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!