Docsity

Trees - Programming Languages and Techniques II - Lecture Slides, Slides of Programming Languages

Partial preview of the text

Download Trees - Programming Languages and Techniques II - Lecture Slides and more Slides Programming Languages in PDF only on Docsity!

Trees

docsity.com

Definition of a tree

 A tree is a node with a value and zero or more children

 Depending on the needs of the program, the children may or may not be ordered

 A tree has a root, internal

nodes, and leaves

 Each node contains an

element and has branches

leading to other nodes (its

children)

 Each node (other than the

root) has a parent

 Each node has a depth

(distance from the root)

A

B C D E

F G H I J K

L M N

docsity.com

Data structure for a tree

 Each node in a tree has an arbitrary number of children, so we

need something that will hold an arbitrary number of nodes, such

as an ArrayList

class Tree { V value; ArrayList children; }

 If we don’t care about the order of children, we might use a Set

instead of a ArrayList

docsity.com

ADT for a tree

 It must be possible to:

 Construct a new tree

 If a tree can be empty, this may require a header node

 Add a child to a node

 Get (iterate through) the children of a node

 Access (get and set) the value in a node

 It should probably be possible to:

 Remove a child (and the subtree rooted at that child)

 Get the parent of a node

docsity.com

Family trees

 It turns out that a tree is not a good way to

represent a family tree

 Every child has two parents, a mother and a father

 Parents frequently remarry

 An “upside down” binary tree almost works

 Since it is a biological fact (so far) that every child has

exactly two parents, we can use left child = father and

right child = mother

 The terminology gets a bit confusing

 If you could go back far enough, it becomes a

mathematical certainty that the mother and father have

some ancestors in common

docsity.com

Part of a genealogy

Isaac

David Paula

Steven Danielle

Winfred Carol

Chester Elaine Eugene Pauline

docsity.com

Trees for expressions and statements

 Examples:

The expression x > y? x : y

x

x

y

y The statement if (x > y) max = x; else max = y;

y

if

x y (^) max x max

docsity.com

More trees for statements

while (n >= 1) {

exp = x * exp;

n--;

for (int i = 0; i < n; i++)

a[i] = 0;

while

=

n 1

exp

exp

n

x

for

i

int

a

i n^ i^ [ ]^0

i

docsity.com