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.

382<br />

Creating Trees<br />

Figure 5-7:<br />

A tree can<br />

organize<br />

names<br />

alphabetically<br />

by<br />

last name.<br />

A B • • • Z<br />

Bally, David Burkins, John<br />

To save the name David Bally, the computer stores the name under the B<br />

node. To save the name John Burkins, the computer also stores this name<br />

under the B node. To determine whether to store this new name be<strong>for</strong>e or<br />

after any existing data, the computer examines the data and sorts it alphabetically.<br />

In this way, the tree data structure not only stores data, but sorts<br />

and organizes it as well.<br />

If you had a long list of names stored in an array or a collection, finding a<br />

name would require searching through the entire array or collection. However,<br />

if that same list of names is stored in a tree, a name would be much<br />

simpler to find because you’d only need to look at the first letter of a<br />

person’s last name to find where it might be stored.<br />

So if you want to find the name John Bally, start at the B node and ignore any<br />

data stored under the other nodes. This makes searching and retrieving data<br />

much faster than other types of data structures, which is why trees are so<br />

commonly used in databases.<br />

Binary trees<br />

A variation of an ordered tree is a binary tree. Unlike an ordinary tree, every<br />

node in a binary tree has at the most two nodes connected underneath. To<br />

sort data, the left node contains values less than its parent node whereas the<br />

right node contains values greater than its parent node, as shown in Figure 5-8.<br />

By limiting each node to a maximum of two connected nodes, binary trees<br />

make searching and sorting data fast and efficient.<br />

10<br />

Figure 5-8:<br />

Binary trees<br />

store and<br />

sort data<br />

by value.<br />

4<br />

8<br />

9<br />

11<br />

12<br />

19

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

Saved successfully!

Ooh no, something went wrong!