19.09.2015 Views

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

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

<br />

<br />

<br />

<br />

<br />

<br />

<br />

<br />

<br />

<br />

<br />

<br />

<br />

<br />

<br />

import java.util.ArrayList;<br />

public class RBTree extends BinaryTree {<br />

/** Create a default RB tree */<br />

public RBTree() {<br />

}<br />

/** Create an RB tree from an array of elements */<br />

public RBTree(E[] elements) {<br />

super(elements);<br />

}<br />

/** Override createNewNode <strong>to</strong> create an RBTreeNode */<br />

protected RBTreeNode createNewNode(E e) {<br />

return new RBTreeNode(e);<br />

}<br />

/** Override the insert method <strong>to</strong> balance the tree if necessary */<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 />

ArrayList path = path(e);<br />

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

// u is the last node in the path. u contains element e<br />

RBTreeNode u = (RBTreeNode)(path.get(i));<br />

23

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

Saved successfully!

Ooh no, something went wrong!