15.04.2018 Views

programming-for-dummies

Create successful ePaper yourself

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

Taking Action on Trees 387<br />

10<br />

8<br />

12<br />

7<br />

Start at the root node. Since 7 is<br />

less than 10, traverse the left<br />

sub-tree.<br />

4<br />

9<br />

11<br />

19<br />

10<br />

Compare 7 with the first node<br />

on the left sub-tree. Since 7 is<br />

less than 8, traverse the left<br />

sub-tree.<br />

7 8<br />

12<br />

4<br />

9<br />

11<br />

19<br />

10<br />

Figure 5-12:<br />

Inserting<br />

new data in<br />

an ordered<br />

binary tree.<br />

Compare 7 with the next node on<br />

the left sub-tree. Since 7 is<br />

greater than 4, add the 7 node to<br />

the right of the 4 node.<br />

If you delete data and immediately add it back to the tree again, the tree<br />

looks different because reinserting the data sorts and organizes it based on<br />

the existing data. So if you delete the 12 node and immediately add it back<br />

again, it now appears as a left node under the 19 node.<br />

Pruning and grafting sub-trees<br />

A sub-tree is a smaller tree, such as part of an existing tree. Rather than<br />

delete a single node, it’s possible to delete an entire sub-tree, which is<br />

known as pruning a tree, as shown in Figure 5-14.<br />

4<br />

8<br />

7<br />

9<br />

11<br />

12<br />

19<br />

Book III<br />

Chapter 5<br />

Graphs and Trees

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

Saved successfully!

Ooh no, something went wrong!