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.

386<br />

Taking Action on Trees<br />

1. Traverse the left sub-tree using in-order.<br />

2. Visit the root node.<br />

3. Traverse the right sub-tree by using in-order.<br />

Postorder traversal<br />

Postorder traversal traverses the left and right sub-trees first and then visits<br />

the root node, as follows:<br />

1. Traverse the left sub-tree in postorder.<br />

2. Traverse the right sub-tree in postorder.<br />

3. Visit the root node.<br />

Level order traversal<br />

Level order traversal starts at the top level of a tree and traverses the row of<br />

nodes on the same level from left to right. Then it drops to the next lower<br />

level and repeats the process all over again.<br />

When writing actual code to traverse a tree, it’s often easier to write a recursive<br />

subprogram that calls itself and traverses a successively smaller part of<br />

the tree (sub-tree) until it finally stops.<br />

Adding new data<br />

Adding data to a linear structure, like a collection or a stack, is straight<strong>for</strong>ward<br />

because the data structure simply gets bigger. Adding data to a tree is<br />

slightly more complicated because you can add new data at the end of a tree<br />

(on one of its leaf nodes) or anywhere in the middle of the tree.<br />

In an unordered tree, you can insert data anywhere, but in an ordered binary<br />

tree, inserting new data means sorting the data at the same time, as shown<br />

in Figure 5-12.<br />

The order that you store data determines the position of that data in a tree<br />

because newly added data gets added based on the existing data’s values.<br />

Deleting data<br />

Deleting data from a tree can cause special problems because after deleting<br />

data, you may need to rearrange any nodes that were underneath the<br />

deleted data, as shown in Figure 5-13.

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

Saved successfully!

Ooh no, something went wrong!