9/16/2010
1
TREES
Lecture 9
CS2110 – Fall 2009
Tree Overview
2
±
Tree
: recursive data structure
(similar to list)
±
Each cell may have zero or
more
successors
(children)
±
Each cell has exactly one
predecessor
(parent) except
5
4
789
2
5
4
7
8
2
the
root
, which has none
±
All cells are reachable from
root
±
Binary tree
: tree in which each
cell can have at most two
children: a left child and a
right child
General tree
Binary tree
5
4
78
Not a tree
5
6
8
Listlike tree
Tree Terminology
3
±
M is the
root
of this tree
±
G is the
root
of the
left subtree
of M
±
B, H, J, N, and S are
leaves
±
N is the
left child
of P; S is the
right
child
P is the
paren
of N
M
G
W
±
P is the
parent
±
M and G are
ancestors
of D
±
P, N, and S are
descendants
of W
±
Node J is at
depth
2 (i.e.,
depth
=
length of path from root = number of
edges)
±
Node W is at
height
2 (i.e.,
height
=
length of longest path to a leaf)
±
A collection of several trees is called
a .
..?
P
J
D
N
H
B
S
Class for Binary Tree Cells
4
class
TreeCell<T> {
private
T
datum
;
private
TreeCell<T>
left
,
right
;
public
TreeCell(T x) {
datum
= x; }
public
TreeCell(T x, TreeCell<T> lft,
TreeCell<T> rgt) {
datum
= x;
left
= lft;
right
= rgt;
}
more methods: getDatum, setDatum,
getLeft, setLeft, getRight, setRight
}
...
new
TreeCell
<String>
("hello") .
..
Class for General Trees
5
class
GTreeCell {
private
Object
datum
;
private
GTreeCell
left
;
private
GTreeCell
sibling
;
appropriate getter and
5
4
2
7
8
3
1
General
tree
setter methods
}
5
4
2
7
83
1
Tree
represented
using
GTreeCell
Parent node points directly
only to its leftmost child
Leftmost child has pointer to
next sibling, which points to
next sibling, etc.
Applications of Trees
6
±
Most languages (natural and computer) have a
recursive, hierarchical structure
±
This structure is
implicit
in ordinary textual
representation
±
Recursive structure can be made
explicit
by
representing sentences in the language as trees:
Abstract Syntax Trees
(ASTs)
±
ASTs are easier to optimize, generate code from, etc.
than textual representation
±
A
parser
converts textual representations to AST
This preview has intentionally blurred sections. Sign up to view the full version.
View Full Document9/16/2010
2
Example
7
±
Expression grammar:
±
E
→
integer
±
E
→
(E + E)
±
In textual representation
34
34
(2 + 3)
+
Text
AST Representation
±
This is the end of the preview. Sign up
to
access the rest of the document.
 Fall '07
 FRANCIS

Click to edit the document details