23.11.2014 Views

Data Structures and Algorithms in Java[1].pdf - Fulvio Frisone

Data Structures and Algorithms in Java[1].pdf - Fulvio Frisone

Data Structures and Algorithms in Java[1].pdf - Fulvio Frisone

SHOW MORE
SHOW LESS

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

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

Figure 10.26: Red-black tree associated with the (2,4)<br />

tree of Figure 10.20. Each external node of this red-black<br />

tree has 4 black ancestors (<strong>in</strong>clud<strong>in</strong>g itself); hence, it has<br />

black depth 3. We use the color blue <strong>in</strong>stead of red. Also,<br />

we use the convention of giv<strong>in</strong>g an edge of the tree the<br />

same color as the child node.<br />

As for previous types of search trees, we assume that entries are stored at the <strong>in</strong>ternal<br />

nodes of a red-black tree, with the external nodes be<strong>in</strong>g empty placeholders. Also, we<br />

assume that the external nodes are actual nodes, but we note that, at the expense of<br />

slightly more complicated methods, external nodes could be null.<br />

We can make the red-black tree def<strong>in</strong>ition more <strong>in</strong>tuitive by not<strong>in</strong>g an <strong>in</strong>terest<strong>in</strong>g<br />

correspondence between red-black trees <strong>and</strong> (2,4) trees, as illustrated <strong>in</strong> Figure 10.27.<br />

Namely, given a red-black tree, we can construct a correspond<strong>in</strong>g (2,4) tree by<br />

merg<strong>in</strong>g every red node v <strong>in</strong>to its parent <strong>and</strong> stor<strong>in</strong>g the entry from v at its parent.<br />

Conversely, we can transform any (2,4) tree <strong>in</strong>to a correspond<strong>in</strong>g red-black tree by<br />

color<strong>in</strong>g each node black <strong>and</strong> perform<strong>in</strong>g the follow<strong>in</strong>g transformation for each<br />

<strong>in</strong>ternal node v:<br />

• If v is a 2-node, then keep the (black) children of v as is.<br />

• If v is a 3-node, then create a new red node w, give v's first two (black) children to<br />

w, <strong>and</strong> make w <strong>and</strong> v's third child be the two children of v.<br />

• If v is a 4-node, then create two new red nodes w <strong>and</strong> z, give v's first two (black)<br />

children to w, give v's last two (black) children to z, <strong>and</strong> make w <strong>and</strong> z be the two<br />

children of v.<br />

642

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

Saved successfully!

Ooh no, something went wrong!