15.04.2018 Views

programming-for-dummies

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

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

Taking Action on Trees 385<br />

Traversing a tree<br />

When you store data in an array or a collection, that data is stored in a line<br />

so you can search the entire data structure by starting at one end and examining<br />

each data chunk one by one until you get to the end. However, trees<br />

are different because they offer multiple branches.<br />

To search a tree, the computer must examine multiple nodes exactly once,<br />

which is known as traversing a tree. Four popular ways to search a tree, as<br />

shown in Figure 5-11, include<br />

Figure 5-11:<br />

The four<br />

different<br />

ways to<br />

traverse<br />

a tree.<br />

4<br />

8<br />

9<br />

10<br />

11<br />

12<br />

19<br />

Preorder: 10, 8, 4, 9, 12, 11, 19<br />

In-order: 4, 8, 9, 10, 11, 12, 19<br />

Postorder: 4, 9, 8, 11, 19, 12, 10<br />

Level order: 10, 8, 12, 4, 9, 11, 19<br />

✦ Preorder<br />

✦ In-order<br />

✦ Postorder<br />

✦ Level order<br />

Preorder traversal<br />

Preorder traversal starts at the top of a tree (the root node) and then traverses<br />

the left nodes. When it reaches a leaf node, it backtracks and goes<br />

down the right nodes, as follows:<br />

Book III<br />

Chapter 5<br />

Graphs and Trees<br />

1. Visit the root node.<br />

2. Traverse the left sub-tree in preorder.<br />

3. Traverse the right sub-tree in preorder.<br />

In-order traversal<br />

When traversing an ordered binary tree, the in-order traversal retrieves data<br />

in order by following these steps:

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

Saved successfully!

Ooh no, something went wrong!