2/23/2011
1
CS/ENGRD 2110
ObjectOriented Programming
and Data Structures
Spring 2010
Thorsten Joachims
Lecture 8: Trees
Tree Overview
•
Tree
: recursive data
structure (similar to list)
–
Each cell may have zero or
more
successors
(children)
–
Each cell has exactly one
predecessor
(parent)
except the
root
, which has
none
–
Cells without children are
called
leaves
–
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
2
5
4
7
8
9
2
General tree
5
4
7
8
2
Binary tree
5
4
7
8
Not a tree
5
6
8
Listlike tree
Tree Terminology
•
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
parent
of N
•
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
...?
3
M
G
W
P
J
D
N
H
B
S
Class for Binary Tree Cells
class TreeCell<T> {
private T datum;
private TreeCell<T> left, right;
public TreeCell(T x) {
datum = x; left = null; right = null;
}
public TreeCell(T x, TreeCell<T> lft,
TreeCell<T> rgt) {
datum = x;
left = lft;
right = rgt;
}
more methods:
getDatum, setDatum, getLeft,
setLeft, getRight, setRight
}
4
... new TreeCell<String>("hello") .
..
Class for General Trees
class GTreeCell {
private Object datum;
private GTreeCell left;
private GTreeCell sibling;
appropriate getter and
setter methods
}
5
5
4
7
8
9
2
7
8
3
1
5
4
7
8
9
2
7
8
3
1
General
tree
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
•
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
6
This preview has intentionally blurred sections. Sign up to view the full version.
View Full Document2/23/2011
2
Example
•
Expression
grammar:
–
E → integer
–
E → (E + E)
•
In textual
representation
–
Parentheses show
hierarchical structure
•
In tree
representation
–
Hierarchy is explicit in
the structure of the tree
7
34
34
(2 + 3)
+
2
3
((2+3) + (5+7))
+
2
3
5
7
+
+
This is the end of the preview.
Sign up
to
access the rest of the document.
 Spring '07
 FRANCIS
 ObjectOriented Programming, Data Structures

Click to edit the document details