06.09.2021 Views

How to Think Like a Computer Scientist - Learning with Python, 2008a

How to Think Like a Computer Scientist - Learning with Python, 2008a

How to Think Like a Computer Scientist - Learning with Python, 2008a

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.

Chapter 20<br />

Trees<br />

<strong>Like</strong> linked lists, trees are made up of nodes. A common kind of tree is a binary<br />

tree, in which each node contains a reference <strong>to</strong> two other nodes (possibly null).<br />

These references are referred <strong>to</strong> as the left and right subtrees. <strong>Like</strong> list nodes, tree<br />

nodes also contain cargo. A state diagram for a tree looks like this:<br />

tree<br />

cargo 1<br />

left<br />

right<br />

cargo 2 cargo 3<br />

left right left right<br />

None None None None<br />

To avoid cluttering up the picture, we often omit the Nones.<br />

The<strong>to</strong>pofthetree(thenodetree refers <strong>to</strong>) is called the root. In keeping <strong>with</strong><br />

the tree metaphor, the other nodes are called branches and the nodes at the tips<br />

<strong>with</strong> null references are called leaves. It may seem odd that we draw the picture<br />

<strong>with</strong> the root at the <strong>to</strong>p and the leaves at the bot<strong>to</strong>m, but that is not the strangest<br />

thing.<br />

To make things worse, computer scientists mix in another metaphor—the family<br />

tree. The <strong>to</strong>p node is sometimes called a parent and the nodes it refers <strong>to</strong> are its<br />

children. Nodes <strong>with</strong> the same parent are called siblings.

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

Saved successfully!

Ooh no, something went wrong!