Professional Documents
Culture Documents
leave
s
branch
es
roo
t
branche
s
leave
s
nodes
What is a Tree
A tree is a finite
nonempty set of
elements.
It is an abstract model
of a hierarchical
structure. consists of
nodes with a parentchild relation.
Applications:
Organization charts
File systems
Programming
environments
ComputersRUs
Sales
US
Europe
Manufacturing
International
Asia
Laptops
Canada
R&D
Desktops
Tree Terminology
subtree
Tree Properties
A
Property
Value
Number of nodes
Height
Root Node
Leaves
Interior nodes
Ancestors of H
Descendants of B
Siblings of E
Right subtree of A
Degree of this tree
Tree ADT
We use positions to
abstract nodes
Generic methods:
integer size()
boolean isEmpty()
objectIterator elements()
positionIterator
positions()
Accessor methods:
position root()
position parent(p)
positionIterator
children(p)
Query methods:
boolean isInternal(p)
boolean isExternal(p)
boolean isRoot(p)
Update methods:
swapElements(p, q)
object replaceElement(p, o)
Intuitive Representation of
Tree Node
List Representation
( A ( B ( E ( K, L ), F ), C ( G ), D ( H ( M ), I, J ) ) )
The root comes first, followed by a list of links to sub-trees
Link 1
Link 2
Link n
Trees
Every tree node:
object useful information
children pointers to its children
Data
Data
Data
Data
Data
Data
Data
A Tree Representation
A node is represented
by an object storing
Element
Parent node
Sequence of children
nodes
B
D
Right
Sibling
Tree Traversal
Recursive definition
Preorder:
visit the root
traverse in preorder the children (subtrees)
Postorder
traverse in postorder the children (subtrees)
visit the root
Preorder Traversal
Become Rich
1. Motivations
3
1.1
Enjoy
Life
Algorithm preOrder(v)
visit(v)
for each child w of
v
preorder (w)
9
2. Methods
1.2 Help
Poor
Friends
6
2.1 Get a
CS PhD
7
2.2 Start a
Web Site
3. Success Stories
8
2.3 Acquired
by Google
Postorder Traversal
In a postorder traversal, a
node is visited after its
descendants
Application: compute space
used by files in a directory
and its subdirectories
Algorithm
postOrder(v)
for each child w of
v
postOrder (w)
visit(v)
cs16/
homeworks/
todo.txt
1K
programs/
h1c.doc
3K
h1nc.doc
2K
4
DDR.java
10K
5
Stocks.java
25K
6
Robot.java
20K
Binary Tree
Applications:
arithmetic expressions
decision processes
searching
C
3
A node is represented
by an object storing
Element
Parent node
Left child node
Right child node
B
A
2
a
3
1
Decision Tree
No
Yes
How about coffee?
On expense account?
Yes
No
Yes
No
Starbucks
Spikes
Al Forno
Caf Paragon
Prove by induction.
k
i
k 1
2
2
1
i 0
4
8
5
9
10
11
12
7
13
14
15
4
8
5
9
10
11
12
7
13
14
15
4
8
5
9
10
11
12
7
13
14
15
4
8
5
9
10
11
12
7
13
14
15
1
2
4
8
5
9
3
6
3
5
9 10 11
12 13 14 15
Inorder Traversal
In an inorder traversal a
node is visited after its left
subtree and before its right
subtree
Algorithm inOrder(v)
if isInternal (v)
inOrder (leftChild (v))
visit(v)
if isInternal (v)
inOrder (rightChild (v))
6
2
4
3
7
5
THANK YOU