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.

48.8 Performance of the RBTree Class<br />

<br />

The search, insertion, and deletion times in a red-black tree depend on<br />

the height of the tree. A red-black tree corresponds <strong>to</strong> a 2-4 tree. When<br />

you convert a node in a 2-4 tree <strong>to</strong> red-black tree nodes, you get one<br />

black node and zero, one, or two red nodes as its children, depending on<br />

whether the original node is a 2-node, 3-node, or 4-node. So, the height<br />

of a red-black tree is at most as twice that of its corresponding 2-4<br />

tree. Since the height of a 2-4 tree is log n , the height of a red-black<br />

tree is 2 log n .<br />

<br />

A red-black tree has the same time <strong>com</strong>plexity as an AVL tree, as shown<br />

in Table 48.1. In general, a red-black is more efficient than an AVL<br />

tree, because a red-black tree requires only one time restructuring of<br />

the nodes for insert and delete operations.<br />

<br />

A red-black tree has the same time <strong>com</strong>plexity as a 2-4 tree, as shown in<br />

Table 48.1. In general, a red-black is more efficient than a 2-4 tree<br />

for two reasons:<br />

1. A red-black tree requires only one-time restructuring of the nodes<br />

for insert and delete operations. However, a 2-4 tree may require<br />

many splits for an insert operation and fusion for a delete<br />

operation.<br />

2. A red-black tree is a binary search tree. A binary tree can be<br />

implemented more space efficiently than a 2-4 tree, because a node<br />

in a 2-4 tree has at most three elements and four children. Space<br />

is wasted for 2-nodes and 3-nodes in a 2-4 tree.<br />

Table 48.1<br />

Time Complexities for Methods in RBTree, AVLTree, and Tree234<br />

Meh<strong>to</strong>ds Red-Black Tree AVL Tree 2-4 Tree<br />

search(e: E) (logn)<br />

insert(e: E) (logn)<br />

O O (logn)<br />

O(log n)<br />

O O (logn)<br />

O(log n)<br />

delete(e: E) O (logn)<br />

O (logn)<br />

O(logn)<br />

getSize() O (1)<br />

O (1)<br />

O(1)<br />

isEmpty() O (1)<br />

O (1)<br />

O(1)<br />

Listing 48.5 gives an empirical test of the performance of AVL trees, 2-<br />

4 trees, and red-black trees.<br />

Listing 48.5 TreePerformanceTest.java<br />

<br />

<br />

<br />

<br />

<br />

<br />

34

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

Saved successfully!

Ooh no, something went wrong!