*This preview shows
pages
1–3. Sign up to
view the full content.*

3/1/2011
1
CS/ENGRD 2110
Object-Oriented Programming
and Data Structures
Spring 2010
Thorsten Joachims
Lecture 9: 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
List-like 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

**sections.**

*blurred***to view the full version.**

*Sign up*3/1/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

This is the end of the preview. Sign up
to
access the rest of the document.