Download - Chapter 6 Trees
U n
i v
e r
s i t
y
o f
H
a i l
1ICS 202 2011 spring Data Structures and Algorithms
U n
i v
e r
s i t
y
o f
H
a i l
2
Outline
1. Basics
2. N-ary Trees
3. Binary Trees
4. Tree Traversals
5. Expression Trees
6. Implementing Trees
• Tree Traversals
• Tree Enumerations
• General Trees
• N-ary Trees
• Binary Trees
• Binary Tree Traversals
• Comparing Trees
• Applications
U n
i v
e r
s i t
y
o f
H
a i l
Lec 1
U n
i v
e r
s i t
y
o f
H
a i l
4
1. Basics
A tree is anon-linear data structure
A tree is often used to represent a hierarchy
Clerk
President
Vice president division A
Manager dept. A1
Clerk Clerk Clerk Clerk Clerk
Manager dept. A2 Manager dept. B1
Vice president division B
U n
i v
e r
s i t
y
o f
H
a i l
5
1. Basics
Definition 1
A tree is a finite, non-empty set of nodes,
1 2{ } ... nT r T T T
with the following properties
1. A chosen node of the set, r, is called the root of the tree;
2. The remaining nodes are subsets, T1, T2, …, Tn, each of each is
a tree.
U n
i v
e r
s i t
y
o f
H
a i l
6
1. Basics
{ }aT A
A
C
B
D
GE
F MJH
I K L{ ,{ }}bT B C
{ ,{ ,{ }},{ ,{ ,{ }},{ ,{ },{ }},{ }}}cT D E F G H I J K L m
U n
i v
e r
s i t
y
o f
H
a i l
ICS 202 2007-2 Data Structures and Algorithms Dr. Youssef Harrath 7
1. Basics
Terminology:
1 2{ , , ,..., }, 0}nT r T T T n Consider a tree
• The degree of a node is the number of subtrees associated with that
node
• A node of degree zero has no subtrees. Such a node is called a leaf.
• Each root ri of subtree Ti of tree T is called a child of r.
• The root node r of tree T is the parent of all the roots ri of the
subtrees Ti, 1 < i n. The term grandparent.
• Two roots ri and rj of distinct subtrees Ti and Tj of tree T are called
siblings(brothers).
U n
i v
e r
s i t
y
o f
H
a i l
ICS 202 2007-2 Data Structures and Algorithms Dr. Youssef Harrath 8
1. Basics
Definition 2 (Path and Path Length)
- Given a tree T containing the set of nodes R, a path in T is
defined as a non-empty sequence of nodes 1 2{ , ,..., }kP r r r
- The length of path P is k-1.
U n
i v
e r
s i t
y
o f
H
a i l
ICS 202 2007-2 Data Structures and Algorithms Dr. Youssef Harrath 9
1. Basics
1 { } 0
2 { , } 1
3 { , , , } 3
P D Length
P E F length
P D G J K length
D
GE
F MJH
I K L
U n
i v
e r
s i t
y
o f
H
a i l
ICS 202 2007-2 Data Structures and Algorithms Dr. Youssef Harrath 10
1. Basics
D
GE
F MJH
I K L
F
E
D
J M
I
H
G
K L
U n
i v
e r
s i t
y
o f
H
a i l
ICS 202 2007-2 Data Structures and Algorithms Dr. Youssef Harrath 11
1. Basicsclass D
{
class E
{
class F
{
}
} class G {
class H { class I { }}
class J {
class K { } class L { }
class M { } }}
D
GE
F MJH
I K L
U n
i v
e r
s i t
y
o f
H
a i l
ICS 202 2007-2 Data Structures and Algorithms Dr. Youssef Harrath 12
2. N-ary Trees
Definition 3 (N-ary Tree) An N-ary tree T is a finite set of nodes with
the following properties:
- Either the set is empty, T = ; or
- The set consists of a root, R, and exactly N distinct N-ary
trees. That is, the remaining nodes are partitioned into N 0
subsets, T0, T1, …, TN-1, each of which is an N-ary tree such
that T = {R, T0, T1, …, TN-1}.
U n
i v
e r
s i t
y
o f
H
a i l
ICS 202 2007-2 Data Structures and Algorithms Dr. Youssef Harrath 13
1. Basics
{ }aT A
A
{ , , , }aT A
A
Tertiary tree (N = 3)
U n
i v
e r
s i t
y
o f
H
a i l
ICS 202 2007-2 Data Structures and Algorithms Dr. Youssef Harrath 14
1. Basics
C
B
{ ,{ }}bT B CC
B
{ ,{ , , , }, , }bT B C
U n
i v
e r
s i t
y
o f
H
a i l
ICS 202 2007-2 Data Structures and Algorithms Dr. Youssef Harrath 15
2. N-ary Trees
• The empty trees are called external nodes (they have no
subtrees and they appear at the extremities of the tree
(squares)).
• The non-empty trees are called internal nodes (circles).
• A tree can be ordered (if its subtrees are ordered) or oriented if
the order of the subtrees doesn’t matter.
U n
i v
e r
s i t
y
o f
H
a i l
ICS 202 2007-2 Data Structures and Algorithms Dr. Youssef Harrath 16
2. N-ary Trees
Theorem 1
An N-ary tree with n 0 internal nodes contains (N-1)n + 1 external
Theorem 2
Consider an N-ary tree of height h 0. The maximum number of
internal nodes in T is given by: 1 1
1
hN
N
The height of a node ri in a tree is the length of the longest path from
node ri to a leaf.
U n
i v
e r
s i t
y
o f
H
a i l
ICS 202 2007-2 Data Structures and Algorithms Dr. Youssef Harrath 17
2. N-ary Trees
Theorem 3
Consider an N-ary tree of height h 0. The maximum number of leaf
nodes T is hN
U n
i v
e r
s i t
y
o f
H
a i l
ICS 202 2007-2 Data Structures and Algorithms Dr. Youssef Harrath 18
3. Binary Trees
Definition 4 (Binary Tree) A binary tree T is a finite set of nodes with
the following properties:
- Either the set is empty, T = ; or
- The set consists of a root, r, and exactly two distinct binary
trees TL, and TR, T = {r, TL, TR}.
TL is called the left subtree of T, and the tree TR is called the right
subtree of T.
U n
i v
e r
s i t
y
o f
H
a i l
ICS 202 2007-2 Data Structures and Algorithms Dr. Youssef Harrath 19
3. Binary Trees
Binary trees are almost considered to be ordered trees (the
above two binary trees are different).
B
A
B
A
U n
i v
e r
s i t
y
o f
H
a i l
ICS 202 2007-2 Data Structures and Algorithms Dr. Youssef Harrath 20
4. Tree Traversals
There are many different algorithms for manipulating trees.
A most common characteristic of these algorithms their visit of all
nodes in the tree (called a tree traversal).
There are essentially two different traversal ways: depth-first
traversal and breadth-first traversal.
Some depth-first traversals can be preorder, inorder, or, postorder
traversals.
U n
i v
e r
s i t
y
o f
H
a i l
ICS 202 2007-2 Data Structures and Algorithms Dr. Youssef Harrath 21
4. Tree Traversals
D
G
B
C E
F I
H
A depth = 0
depth = 1
depth = 2
depth = 3
U n
i v
e r
s i t
y
o f
H
a i l
ICS 202 2007-2 Data Structures and Algorithms Dr. Youssef Harrath 22
4. Tree Traversals
Preorder Traversal
The first depth-first traversal method is called preorder traversal.
Preorder traversal is defined as follows
1. Visit the root first, and then
2. Do a preorder traversal each of the subtrees of the root one-by-one in
the order given.
In the case of a binary tree, the algorithm becomes
1. Visit the root first, and then
2. Traverse the left subtree, and then
3. Traverse the right subtree
U n
i v
e r
s i t
y
o f
H
a i l
ICS 202 2007-2 Data Structures and Algorithms Dr. Youssef Harrath 23
4. Tree Traversals
Preorder traversal
A, B, C, D, E, F, G, H, I
D
G
B
C E
F I
H
A depth = 0
depth = 1
depth = 2
depth = 3
U n
i v
e r
s i t
y
o f
H
a i l
ICS 202 2007-2 Data Structures and Algorithms Dr. Youssef Harrath 24
4. Tree Traversals
Postorder Traversal
The second depth-first traversal method is called postorder
traversal.
Postorder traversal is defined as follows
1. Do a postorder traversal each of the subtrees of the root one-by-one
in the order given, and then
2. Visit the root.
In the case of a binary tree, the algorithm becomes
1. Traverse the left subtree, and then
2. Traverse the right, and then
3. Visit the root.
U n
i v
e r
s i t
y
o f
H
a i l
ICS 202 2007-2 Data Structures and Algorithms Dr. Youssef Harrath 25
4. Tree Traversals
Postorder traversal
C, B, F, G, E, I, H, D, A
D
G
B
C E
F I
H
A depth = 0
depth = 1
depth = 2
depth = 3
U n
i v
e r
s i t
y
o f
H
a i l
ICS 202 2007-2 Data Structures and Algorithms Dr. Youssef Harrath 26
4. Tree Traversals
Inorder Traversal
The third depth-first traversal method is called inorder traversal
(available only for binary trees).
Inorder traversal is defined as follows
1. Traverse the left subtree, and then
2. Visit the root, and then
3. Traverse the right subtree.
U n
i v
e r
s i t
y
o f
H
a i l
ICS 202 2007-2 Data Structures and Algorithms Dr. Youssef Harrath 27
4. Tree Traversals
Inorder Traversal
B, C, A, F, E, G, D, I, H
D
G
B
C E
F I
H
A depth = 0
depth = 1
depth = 2
depth = 3
U n
i v
e r
s i t
y
o f
H
a i l
ICS 202 2007-2 Data Structures and Algorithms Dr. Youssef Harrath 28
4. Tree Traversals
Breadth-First Traversal
The Breadth-first traversals are non-recursive traversals and
better understood.
A Breadth-first traversal visits the nodes of a tree in the order of
their depth.
It visits first nodes at depth zero, then all nodes at depth one, and
so on.
At each depth, the nodes are visited from left to right.
U n
i v
e r
s i t
y
o f
H
a i l
ICS 202 2007-2 Data Structures and Algorithms Dr. Youssef Harrath 29
4. Tree Traversals
Inorder Traversal
A, B, D, C, E, H, F, G, I
D
G
B
C E
F I
H
A depth = 0
depth = 1
depth = 2
depth = 3
U n
i v
e r
s i t
y
o f
H
a i l
Lec 2
U n
i v
e r
s i t
y
o f
H
a i l
ICS 202 2007-2 Data Structures and Algorithms Dr. Youssef Harrath 31
5. Expression Trees
a
c
b -
d
e
+
/ ( )a b c d e
- Leaves = variables (a, b, …)
- Non-terminal nodes = operators (+,
-, , )
- The non-terminal nodes have either
one or two non-empty subtrees
(binary or unary operator).
U n
i v
e r
s i t
y
o f
H
a i l
ICS 202 2007-2 Data Structures and Algorithms Dr. Youssef Harrath 32
5. Expression Trees
a
c
b -
d
e
+
/ ( )a b c d e
- Inorder traversal of the expression
tree: a, , b, +, c, -, d, , e
- Except the missing parentheses,
the order in which the symbols
appear is the same as in the
expression.
U n
i v
e r
s i t
y
o f
H
a i l
ICS 202 2007-2 Data Structures and Algorithms Dr. Youssef Harrath 33
5. Expression Trees
To apply an inorder traversal and take into account the level of
operators, we process as following:
When the inorder traversal encounters(found) a terminal node
(variable or constant), prints it out
When it encounters a non-terminal node, it does the following:
Print a left parenthesis, and then
Traverse the left subtree, and then
Print the root, and then
Traverse the right subtree, and then
Print a right parenthesis
U n
i v
e r
s i t
y
o f
H
a i l
ICS 202 2007-2 Data Structures and Algorithms Dr. Youssef Harrath 34
5. Expression Trees
a
c
b -
d
e
+
( ) (( ) ))a b c d e
U n
i v
e r
s i t
y
o f
H
a i l
ICS 202 2007-2 Data Structures and Algorithms Dr. Youssef Harrath 35
Comparable
Container
Tree
AbstractObject
AbstractContainer
GeneralTree
NaryTree
BinaryTree
AbstractTree
6. Implementing Trees
U n
i v
e r
s i t
y
o f
H
a i l
ICS 202 2007-2 Data Structures and Algorithms Dr. Youssef Harrath 36
6. Implementing Trees
public interface Tree extends Container
{
Object getKey (); // returns the object contained in the root of the tree
Tree getSubtree (int i); // returns the ith subtree of the tree
boolean isEmpty (); // returns true if the root is empty
boolean isLeaf (); // returns true if the root of the tree is a leaf
int getDegree (); // returns the degree of the root
int getHeight (); // returns the height of the tree
void depthFirstTraversal (PrePostVisitor visitor);
void breadthFirstTraversal (Visitor visitor);
} // all the nodes are systematically visited either in depth-first or breadth-first traversal
U n
i v
e r
s i t
y
o f
H
a i l
ICS 202 2007-2 Data Structures and Algorithms Dr. Youssef Harrath 37
6. Implementing Trees: Tree traversal (depth-first)
public abstract class AbstractTree extends AbstractContainer implements Tree
{
public void depthFirstTraversal (PrePostVisitor visitor)
{
if (visitor.isDone ())
return;
if (!isEmpty ())
{
visitor.preVisit (getKey ()); // visit the root
for (int i = 0; i < getDegree (); ++i) // visit the nodes under the root
getSubtree (i).depthFirstTraversal (visitor); // recursive
visitor.postVisit (getKey ()); // visit subtree
}
}
}
U n
i v
e r
s i t
y
o f
H
a i l
ICS 202 2007-2 Data Structures and Algorithms Dr. Youssef Harrath 38
public interface PrePostVisitor
{
void preVisit (Object object);
void inVisit (Object object);
void postVisit (Object object);
boolean isDone ();
}
6. Implementing Trees: Tree traversal (depth-first)
U n
i v
e r
s i t
y
o f
H
a i l
ICS 202 2007-2 Data Structures and Algorithms Dr. Youssef Harrath 39
public abstract class AbstractPrePostVisitor implements PrePostVisitor
{
public void preVisit (Object object) {}
public void inVisit (Object object) {}
public void postVisit (Object object) {}
public boolean isDone ()
{
return false;
}
}
6. Implementing Trees: Tree traversal (depth-first)
U n
i v
e r
s i t
y
o f
H
a i l
ICS 202 2007-2 Data Structures and Algorithms Dr. Youssef Harrath 40
public class PreOrder extends AbstractPrePostVisitor
{ // using the visitor interface
protected Visitor visitor;
public PreOrder (Visitor visitor)
{
this.visitor = visitor;
}
public void preVisit (Object object)
{
visitor.visit (object);
}
public boolean isDone ()
{
return visitor.isDone ();
}
}
6. Implementing Trees: Tree traversal (depth-first)
U n
i v
e r
s i t
y
o f
H
a i l
ICS 202 2007-2 Data Structures and Algorithms Dr. Youssef Harrath 41
public class InOrder extends AbstractPrePostVisitor
{
protected Visitor visitor;
public InOrder (Visitor visitor)
{
this.visitor = visitor;
}
public void inVisit (Object object)
{
visitor.visit (object);
}
public boolean isDone ()
{
return visitor.isDone ();
}
}
6. Implementing Trees: Tree traversal (depth-first)
U n
i v
e r
s i t
y
o f
H
a i l
ICS 202 2007-2 Data Structures and Algorithms Dr. Youssef Harrath 42
public class PostOrder extends AbstractPrePostVisitor
{
protected Visitor visitor;
public PostOrder (Visitor visitor)
{
this.visitor = visitor;
}
public void postVisit (Object object)
{
visitor.visit (object);
}
public boolean isDone ()
{
return visitor.isDone ();
}
}
6. Implementing Trees: Tree traversal (depth-first)
U n
i v
e r
s i t
y
o f
H
a i l
ICS 202 2007-2 Data Structures and Algorithms Dr. Youssef Harrath 43
Visistor v = new PrintingVisitor ();
Tree t = new SomeTree ();
// …
t.depthFirstTraversal (new PreOrder (v));
t.depthFirstTraversal (new InOrder (v));
t.depthFirstTraversal (new PostOrder (v));
6. Implementing Trees: Tree traversal (depth-first)
U n
i v
e r
s i t
y
o f
H
a i l
ICS 202 2007-2 Data Structures and Algorithms Dr. Youssef Harrath 44
public abstract class AbstractTree extends AbstractContainer implements Tree {
public void breadthFirstTraversal (Visitor visitor) { Queue queue = new QueueAsLinkedList (); if (!isEmpty ())
queue.enqueue (this); // the root node is enqueued firstly while (!queue.isEmpty () && !visitor.isDone ()) {
Tree head = (Tree) queue.dequeue (); // remove the head
visitor.visit (head.getKey ()); // visit the object in head
for (int i = 0; i < head.getDegree (); ++i) { Tree child = head.getSubtree (i); if (!child.isEmpty ())
queue.enqueue (child); // enqueue in order each
// non-empty subtree
} }}
}
6. Implementing Trees: Tree traversal (Breadth-first)
U n
i v
e r
s i t
y
o f
H
a i l
ICS 202 2007-2 Data Structures and Algorithms Dr. Youssef Harrath 45
D
G
B
C E
F I
H
A
6. Implementing Trees: Binary Trees
U n
i v
e r
s i t
y
o f
H
a i l
ICS 202 2007-2 Data Structures and Algorithms Dr. Youssef Harrath 46
6. Implementing Trees: Binary Trees
A
C
B D
HE
F G I
U n
i v
e r
s i t
y
o f
H
a i l
ICS 202 2007-2 Data Structures and Algorithms Dr. Youssef Harrath 47
6. Implementing Trees: Binary Trees
public class BinaryTree extends AbstractTree
{
protected Object key;
protected BinaryTree left;
protected BinaryTree right;
// ...
}
U n
i v
e r
s i t
y
o f
H
a i l
ICS 202 2007-2 Data Structures and Algorithms Dr. Youssef Harrath 48
6. Implementing Trees: Binary Trees
public class BinaryTree extends AbstractTree {
protected Object key; protected BinaryTree left; protected BinaryTree right; public BinaryTree (Object key, BinaryTree left, BinaryTree right) {
this.key = key; this.left = left; this.right = right;
} public BinaryTree () {
this (null, null, null); } public BinaryTree (Object key) {
this (key, new BinaryTree (), new BinaryTree ()); }
}
U n
i v
e r
s i t
y
o f
H
a i l
ICS 202 2007-2 Data Structures and Algorithms Dr. Youssef Harrath 49
6. Implementing Trees: Binary Trees
public class BinaryTree extends AbstractTree
{
protected Object key;
protected BinaryTree left;
protected BinaryTree right;
public void purge ()
{
key = null;
left = null;
right = null;
}
// ...
}
U n
i v
e r
s i t
y
o f
H
a i l
ICS 202 2007-2 Data Structures and Algorithms Dr. Youssef Harrath 50
6. Implementing Trees: Binary Trees
public class BinaryTree extends AbstractTree
{
protected Object key;
protected BinaryTree left;
protected BinaryTree right;
public void depthFirstTraversal (PrePostVisitor visitor)
{
if (!isEmpty ())
{
visitor.preVisit (key);
left.depthFirstTraversal (visitor);
visitor.inVisit (key);
right.depthFirstTraversal (visitor);
visitor.postVisit (key);
}
}
}
U n
i v
e r
s i t
y
o f
H
a i l
// A
// B C
// D E F G
Implementing tree Example
D
CB
E F G
A
U n
i v
e r
s i t
y
o f
H
a i l
import ADTs.*;public class testTree{ public static void main(String[] args) { BinaryTree D = new BinaryTree(new Chr('D')); BinaryTree E = new BinaryTree(new Chr('E')); BinaryTree B = new BinaryTree(new Chr('B'),D,E); BinaryTree F = new BinaryTree(new Chr('F')); BinaryTree G = new BinaryTree(new Chr('G')); BinaryTree C = new BinaryTree(new Chr('C'),F,G); BinaryTree A = (BinaryTree) new BinaryTree(new Chr('A'),B,C); Visitor v = new ChrPrintingVisitor();
System.out.println("*************PreOrder Traversal***************"); A.depthFirstTraversal(new PreOrder(v)); System.out.println("***************InOrder Traversal**************"); A.depthFirstTraversal(new InOrder(v)); System.out.println("****************PostOrder Traversal*************"); A.depthFirstTraversal(new PostOrder(v)); System.out.println("****************Breadth Traversal***************"); A.breadthFirstTraversal(v);
} }
U n
i v
e r
s i t
y
o f
H
a i l
*************PreOrder Traversal***************ABDECFG***************InOrder Traversal**************DBEAFCG****************PostOrder Traversal*************DEBFGCA****************Breadth Traversal*************** (A B C D E F G )
U n
i v
e r
s i t
y
o f
H
a i l
ICS 202 2007-2 Data Structures and Algorithms Dr. Youssef Harrath 54
6. Implementing Trees: Applications
In chapter 6, we sow how a stack can be used to compute the value
of a postfix expression such as: ab cd e
We are interested in this section in constructing the corresponding
expression tree.
Once the tree is constructed, we can print it in infix or prefix notation.
U n
i v
e r
s i t
y
o f
H
a i l
ICS 202 2007-2 Data Structures and Algorithms Dr. Youssef Harrath 55
6. Implementing Trees: Applications
The symbols in the postfix expression are processed from left to
right as follow:
• If the next symbol in the expression is an operand, a tree composed of a
single node labeled with that operand is pushed onto the stack.
• If the next symbol in the expression is a binary operator, the top two trees
in the stack correspond to its operands. Two trees are popped from the
stack and a new tree is created that has the operator as its root and the
two trees corresponding to the operands as its subtrees. Then the new tree
is pushed onto the stack.
U n
i v
e r
s i t
y
o f
H
a i l
ICS 202 2007-2 Data Structures and Algorithms Dr. Youssef Harrath 56
6. Implementing Trees: Applications
ab cd e
U n
i v
e r
s i t
y
o f
H
a i l
ICS 202 2007-2 Data Structures and Algorithms Dr. Youssef Harrath 57
6. Implementing Trees: Applications
public class ExpressionTree extends BinaryTree {
public ExpressionTree (char c) { super (new Chr (c)); } public static ExpressionTree parsePostfix (Reader in) throws IOException { Stack stack = new StackAsLinkedList (); int i; while ((i = in.read ()) >= 0) // reads one character at a time from the keyboard {
char c = (char) i; if (Character.isLetterOrDigit (c)) stack.push (new ExpressionTree (c)); else if (c == '+' || c == '-' || c == '*' || c =='/') { ExpressionTree result = new ExpressionTree (c); result.attachRight((ExpressionTree) stack.pop()); result.attachLeft ((ExpressionTree) stack.pop()); stack.push (result); }
} return (ExpressionTree) stack.pop (); }
}
U n
i v
e r
s i t
y
o f
H
a i l
ICS 202 2007-2 Data Structures and Algorithms Dr. Youssef Harrath 58
6. Implementing Trees: Applications
public class ExpressionTree extends BinaryTree {
public String toString () { final StringBuffer buffer = new StringBuffer (); PrePostVisitor visitor = new AbstractPrePostVisitor () {
public void preVisit (Object object) { buffer.append ("("); } public void inVisit (Object object) { buffer.append (object); } public void postVisit (Object object) { buffer.append (")"); }
}; depthFirstTraversal (visitor); return buffer.toString (); }
}
U n
i v
e r
s i t
y
o f
H
a i l
ICS 202 2007-2 Data Structures and Algorithms Dr. Youssef Harrath 59
6. Implementing Trees: Applications
Given the input ab/cd-e*+. The program constructs the expression tree
and then forms the infix expression: (((a)/(b))+((c)-(d))*(e))).