Discussion 1B Notes (Week 8, May 21)
TA: Brian Choi (schoi@cs.ucla.edu)
Section Webpage:
http://www.cs.ucla.edu/~schoi/cs32
Trees
Definitions
Yet another data structure -- trees. Just like a linked list, a
tree
consists of nodes (vertices) and links (edges).
A tree is a
hierarchical
structure. That is, a pair of nodes connected by an edge has a parent-child
relationship. The following diagram depicts a simple tree of 8 nodes:
Here, A is the
parent
of B and C. B and C are the
children
of A. Because B and C share the parent, they are
siblings
.
We can also say B is an
ancestor
of F, and G is an
descendant
of A, and so forth. The ancestor of all nodes, A
in this case, is called the
root
of the tree. If you think of this
as a lineage tree, all these terms should be intuitive. In a
pointer-based implementation of a tree, in the node
structure, we may keep one pointer that points to the parent
node, and several pointers that point to the children nodes.
If you look carefully, there is another tree embedded in the
tree (formed by the shaded nodes). A tree within another tree
is called a
subtree
. The shaded subtree in the left figure is
rooted
at B. This
subtree of node B
has 5 nodes. Every
node in the tree can be the root of some subtree. Therefore,
there are a total of 8 subtrees in this tree, rooted at each
node.
A tree with no node is an
empty
tree.
The
height
of a tree is defined to be the number of nodes
on the longest path in the tree, beginning at the root. The
example above has the height of 3.
A node in a tree generally cannot
have an ancestor as its child. This forms a loop in
the structure, as depicted on the left side, and therefore, it is no longer a tree. Also, a
node has only one parent. A tree is considered
malformed
when there are nodes
that violate these rules.
In general, a node can have a variable number of children, as in this tree. There are
special types of trees with a limited number of children per node, which we’ll see
soon.
If you think about it, a tree with each node having only one child is nothing but a linked list. Therefore, a
tree is a general form of linked lists.
Question:
How many edges should there be for a tree of N nodes?
Finally, a node with no children is called a
leaf
.
CS32: Introduction to Computer Science II
Spring 2010
Copyright 2010 Brian Choi
Week 8, Page 1/7
!
#
$
!
#
$
%
&
'
(
!