Chapter 5
Trees
Yi-Fen Liu
Department of IECS, FCU
References:
- E. Horowitz, S. Sahni and S. Anderson-Freed, Fundamentals of Data Structures (2nd Edition)
- Slides are credited from Prof. Chung, NTHU
Outline
• Introduction
• Binary Trees
• Binary Tree Traversals
• Additional Binary Tree Operations
• Threaded Binary Tree
• Heaps
• Binary Search Trees
• Selection Trees
• Forest
Yi-Fen Liu, FCU IECS Data Structures (Ch5) - 2
INTRODUCTION
Introduction (1)
• A tree structure means that the data are
organized so that items of information are
related by branches
• Examples
Yi-Fen Liu, FCU IECS Data Structures (Ch5) - 4
Introduction (2)
Data Structures
Introduction (3)
• Definition (recursively): A tree is a finite set of one
or more nodes such that
– There is a specially designated node called root
– The remaining nodes are partitioned into n≧0 disjoint
set T1,…,Tn, where each of these sets is a tree
– T1,…,Tn are called the subtrees of the root
• Every node in the tree is the root of some subtree
Yi-Fen Liu, FCU IECS Data Structures (Ch5) - 6
Introduction (4)
• Some Terminology
– Node: the item of information plus the branches to each
node
– Degree: the number of subtrees of a node
– Degree of a tree: the maximum of the degree of the nodes
in the tree
– Terminal nodes (or leaf): nodes that have degree zero
– Nonterminal nodes: nodes that don’t belong to terminal
nodes
– Children: the roots of the subtrees of a node X are the
children of X
– Parent: X is the parent of its children.
Yi-Fen Liu, FCU IECS Data Structures (Ch5) - 7
Introduction (5)
• Some Terminology (cont’d)
– Siblings: children of the same parent are said to be siblings
– Ancestors of a node: all the nodes along the path from the
root to that node
– The level of a node: defined by letting the root be at level
one
• If a node is at level l, then it children are at level l+1
– Height (or depth): the maximum level of any node in the
tree
Yi-Fen Liu, FCU IECS Data Structures (Ch5) - 8
Introduction (6)
• Example
– A is the root node Property: (# edges) = (#nodes) - 1
– B is the parent of D and E
– C is the sibling of B
Level
– D and E are the children of B
– D, E, F, G, I are terminal nodes, or leaves A 1
– A, B, C, H are internal nodes
– The level of E is 3 B C
2
– The height (depth) of the tree is 4
– The degree of node B is 2
– The degree of the tree is 3 H
3
– The ancestors of node I is A, C, H
D E F G
– The descendants of node C is F, G, H, I I
4
Data Structures (Ch5) - 9
Introduction (7)
• Representation Of
Trees
– List Representation
• We can write the
figure as a list in
which each of the
subtrees is also a list
– ( A ( B ( E ( K, L ), F ), C
( G ), D ( H ( M ), I, J ) ) )
• The root comes first,
followed by a list of
sub-trees
Data Structures (Ch5) - 10
Introduction (8)
• Representation
Of
Trees (cont’d)
– Left Child-
Right Sibling
Representation
Data Structures (Ch5) - 11
Introduction (9)
• Representation Of
Trees (cont’d)
– Representation
as a degree-two tree
Data Structures (Ch5) - 12
BINARY TREES
Binary Trees (1)
• Binary trees are characterized by the fact that
any node can have at most two branches
• Definition (recursive)
A A – A binary tree is a finite set of nodes that is either
empty or consists of a root and two disjoint binary
B B trees called the left subtree and the right subtree
• Thus the left subtree and the right subtree are
distinguished
• Any tree can be transformed into binary tree
– by left child-right sibling representation
Yi-Fen Liu, FCU IECS Data Structures (Ch5) - 14
Binary Trees (2)
• The abstract data type of binary tree
Binary Trees (3)
• Two special
kinds of binary
trees
– skewed tree
– complete
binary tree
• The all leaf
nodes of these
trees are on
two adjacent
levels
Data Structures (Ch5) - 16
Binary Trees (4)
• Properties of binary trees
– Lemma [Maximum number of nodes]
• The maximum number of nodes on level i of a
binary tree is 2i-1, i 1.
• The maximum number of nodes in a binary tree of
depth k is 2k-1, k1.
Level 1, # of nodes = 21-1 = 1
Level 2, # of nodes = 22-1 = 2
Level 3, # of nodes = 23-1 = 4
Level 4, # of nodes = 24-1 = 8
Binary Trees (5)
– Lemma [Relation between number of leaf nodes and
degree-2 nodes]
• For any nonempty binary tree, T, if n0 is the number
of leaf nodes and n2 is the number of nodes of
degree 2, then n0 = n2 + 1
– These lemmas allow us to define full and complete
binary trees
n2
Data Structures (Ch5) - 18 n0
Binary Trees (6)
• A full binary tree of depth k is a binary tree of depth k having 2k-1 nodes, k
0 (所有的 internal nodes 的 out degree 都是 2, 且所有的 external nodes 都
在同一 level)
• A binary tree with n nodes and depth k is complete iff its nodes correspond
to the nodes numbered from 1 to n in the full binary tree of depth k (最下
一層也就是第 k 層的所有 nodes 都盡量擠在最左邊)
• Lemma: The height of a complete binary tree with n nodes is log2(n+1)
Full Binary Tree Complete Binary Tree
Binary Tree Representations
– Using Array (1)
• Lemma: If a complete binary tree with n nodes is
represented sequentially, then for any node with index i, 1
i n, we have
– Parent(i) is at i /2 if i 1
• If i = 1, i is at the root and has no parent
– LeftChild(i) is at 2i if 2i n
• If 2i n, then i has no left child
– RightChild(i) is at 2i+1 if 2i+1 n A 1
• If 2i +1 n, then i has no right child
[1] [2] [3] [4] [5] [6] [7] B 2 C 3
A B C — D — E
Level 1 D E
Level 2 Level 3 4 5 6 7
Binary Tree Representations
– Using Array (2)
• Waste spaces
– In the worst case, a skewed tree
of depth k requires 2k-1 spaces.
Of these, only k spaces will be
occupied
• Insertion or deletion of nodes
from the middle of a tree
requires the movement of
potentially many nodes to
reflect the change in the level
of these nodes
Yi-Fen Liu, FCU IECS Data Structures (Ch5) - 21
Binary Tree Representations
– Using Link (1)
Yi-Fen Liu, FCU IECS Data Structures (Ch5) - 22
Binary Tree Representations
– Using Link (2)
Data Structures (Ch5) - 23
BINARY TREE TRAVERSALS
Binary Tree Traversals (1)
• How to traverse a tree or visit each node in the tree
exactly once?
– There are six possible combinations of traversal
• LVR, LRV, VLR, VRL, RVL, RLV
– Adopt convention that we traverse left before
right, only 3 traversals remain
• LVR (inorder), LRV (postorder), VLR (preorder)
left_child data right_child
V
L: moving left : R: moving right
visiting
Data Structures (Ch5) - 25
node
Binary Tree Traversals (2)
• Arithmetic Expression using binary
tree
– Inorder traversal (infix expression)
• A/B*C*D+E
– Preorder traversal (prefix expression)
• +**/ABCDE
– Postorder traversal (postfix expression)
• AB/C*D*E+
– Level order traversal
• +*E*D/CAB
Data Structures (Ch5) - 26
Binary Tree Traversals (3)
• Inorder traversal (LVR) (recursive version)
output: A / B * C * D + E
L ptr
V
R
Data Structures (Ch5) - 27
Binary Tree Traversals (4)
• Preorder traversal (VLR) (recursive version)
output: + * * / A B C D E
V
L
R
Data Structures (Ch5) - 28
Binary Tree Traversals (5)
• Postorder traversal (LRV) (recursive version)
output: A B / C * D * E +
L
R
V
Data Structures (Ch5) - 29
Binary Tree Traversals (6)
• Iterative inorder traversal
– we use a stack to simulate recursion
5 4
8 11
3 14
2 17
1
A B
/ *C D* +E
L
V
output: A / B*C * D + E
node
Binary Tree Traversals (7)
• Analysis of inorder (Non-recursive Inorder traversal)
– Let n be the number of nodes in the tree
– Time complexity: O(n)
• Every node of the tree is placed on and removed
from the stack exactly once
– Space complexity: O(n)
• Equal to the depth of the tree which
(skewed tree is the worst case)
Yi-Fen Liu, FCU IECS Data Structures (Ch5) - 31
Level-Order Traversal
– Using Queue (1)
• Level-order traversal
– Method
• We visit the root first, then the root’s left child,
followed by the root’s right child.
• We continue in this manner, visiting the nodes at each
new level from the leftmost node to the rightmost
nodes
– This traversal requires a queue to implement
Yi-Fen Liu, FCU IECS Data Structures (Ch5) - 32
Level-Order Traversal
– Using Queue (2)
output: + * E * D / C A B
2 17 3 14 4 11 5 8
1
*+ E * D / C A B
FIFO
ptr
ADDITIONAL BINARY TREE
OPERATIONS
Additional Binary Tree Operations
– Copying Binary Trees
• Modify the postorder traversal algorithm only slightly to
copy the binary tree
Additional Binary Tree Operations
– Testing Equality
– Binary trees are equivalent if they have the same topology
and the information in corresponding nodes is identical
V
L
R
Yi-Fen Liu, FCU IECS Data Structures (Ch5) - 36
Satisfiability Problem (1)
• Variables x1, x2, …, xn can hold only two possible
values, true or false
– Operators on variables: (and), (or), ¬(not)
• Propositional Calculus Expression
– A variable is an expression
– If x and y are expressions, then ¬x, xy, xy are
expressions
– Parentheses can be used to alter the normal order of
evaluation (¬ > > )
• Example: x1 (x2 ¬x3)
Yi-Fen Liu, FCU IECS Data Structures (Ch5) - 37
Satisfiability Problem (2)
• Satisfiability problem
– Is there an assignment to make an expression true?
• Solution for the Example x1 (x2 ¬x3)
– If x1 and x3 are false and x2 is true
• false (true ¬false) = false true = true
• For n value of an expression, there are 2n possible
combinations of true and false
Yi-Fen Liu, FCU IECS Data Structures (Ch5) - 38
Satisfiability Problem (3)
(x1 ¬x2) (¬ x1 x3) ¬x3
postorder traversal
data
value X3
X1 X3
X2 X1
Satisfiability Problem (4)
• Node structure
– For the purpose of our evaluation algorithm, we assume each
node has four fields
– We define this node structure in C as:
Data Structures (Ch5) - 40
Satisfiability Problem (5)
• Satisfiability function
– To evaluate the tree is
easily obtained by
modifying the original L
recursive postorder R
traversal V
TRUE
node
TRUE
FALSE
FALSE
TRUE T
TRUE
FALSE F FALSE
T TRUE TRUE
FALSE F
Data Structures T TRUE 41
THREADED BINARY TREES
Threaded Binary Trees (1)
• Threads
– The drawback of the binary tree
• Too many null pointers in current representation of
binary trees
– n: number of nodes
• number of non-null links: n-1
• total links: 2n
• null links: 2n-(n-1) = n+1
– Solution: replace these null pointers with some
useful “threads”
Yi-Fen Liu, FCU IECS Data Structures (Ch5) - 43
Threaded Binary Trees (2)
• Rules for constructing the threads
– If ptr->left_child is null,
replace it with a pointer to the node that would
be visited before ptr in an inorder traversal
– If ptr->right_child is null,
replace it with a pointer to the node that would
be visited after ptr in an inorder traversal
Yi-Fen Liu, FCU IECS Data Structures (Ch5) - 44
Threaded Binary Trees (3)
• A Threaded Binary Tree
root A
t: true thread
f: false child dangling
f B f C
D t E t F G
dangling
inorder traversal:
H I
H D I B E A F C G
Data Structures (Ch5) - 45
Threaded Binary Trees (4)
• Two additional fields of the node structure,
left_thread and right_thread
– If ptr->left_thread = TRUE, then ptr->left_child contains a thread
– Otherwise it contains a pointer to the left child
– Similarly for the right_thread
Threaded Binary Trees (5)
• If we don’t want the left pointer of H and the right pointer of
G to be dangling pointers, we may create root node and
assign them pointing to the root node
Data Structures (Ch5) - 47
Threaded Binary Trees (6)
• Inorder traversal of a threaded binary tree
– By using of threads, we can perform an inorder
traversal without using a stack (simplifying the
task)
– Now, we can follow the thread of any node, ptr,
to the “next” node of inorder traversal
• If ptr->right_thread = TRUE, the inorder
successor of ptr is ptr-> right_child by
definition of the threads
• Otherwise we obtain the inorder successor
of ptr by following a path of left_child links
from the right_child of ptr until we reach a
node with left_thread = TRUE
Yi-Fen Liu, FCU IECS Data Structures (Ch5) - 48
Threaded Binary Trees (7)
• Finding the inorder successor (next node) of a node
threaded_pointer insucc(threaded_pointer tree){
threaded_pointer temp;
temp = tree->right_child; tree
if (!tree->right_thread)
while (!temp->left_thread)
temp = temp->left_child;
return temp;
} temp
Inorder
Data Structures (Ch5) - 49
Threaded Binary Trees (8)
• Inorder traversal of a threaded binary tree
void tinorder(threaded_pointer tree){
/* traverse the threaded binary tree inorder */
threaded_pointer temp = tree; output: H D I B E A F C G
for (;;) {
temp = insucc(temp);
if (temp==tree) tree
break;
printf(“%3c”,temp->data);
}
}
Time Complexity: O(n)
Threaded Binary Trees (9)
• Insertion of Threaded Binary Tree
– Insert child as the right child of node parent
A parent
root child
B
X
A parent C
B
D
C X child E F
First Case Second Case
Data Structures (Ch5) - 51
Threaded Binary Trees (10)
• Right insertion in a threaded binary tree
void insert_right(thread_pointer parent, threaded_pointer
child){
/* insert child as the right child of root
parent in a threaded binary tree */
threaded_pointer temp;
child->right_child = parent->right_child; A parent
child->right_thread = parent->right_thread; B
child->left_child = parent;
child->left_thread = TRUE;
parent->right_child = child;
C X child
parent->right_thread = FALSE;
If(!child->right_thread){
A parent temp
temp = insucc(child);
temp->left_child = child; B child
} X
} C
D
First Case
Second Case E F
successor
HEAP
Heaps (1)
• The heap abstract data type
– A max(min) tree is a tree in which the key value in each
node is no smaller (larger) than the key values in its
children
– A max (min) heap is a complete binary tree that is also a
max (min) tree
– Basic Operations
• Creation of an empty heap
• Insertion of a new element into a heap
• Deletion of the largest element from the heap
Yi-Fen Liu, FCU IECS Data Structures (Ch5) - 54
Heaps (2)
• The examples of max heaps and min heaps
– Property: The root of max heap (min heap)
contains the largest (smallest) element
Data Structures (Ch5) - 55
Heaps (3)
• Abstract data type of Max Heap
Heaps (4)
• Queue in Chapter 3: FIFO
• Priority queues
– Heaps are frequently used to implement priority queues
• delete the element with highest (lowest) priority
• insert the element with arbitrary priority
• Heaps is the only way to implement priority queue
Data Structures (Ch5) - 57
Heaps (5)
• Insertion into a Max Heap
– Analysis of insert_max_heap
• The complexity of the insertion function is O(log2 n)
insert 2
51
*n= 6
5
i= 1
6
7
3
[1]
20
21
[2] [3]
parent sink
15 20
52 item upheap
[4] [5] [6] [7]
14 10 2 5 58
Heaps (6)
• Deletion from a max heap
– After deletion, the heap
is still a complete binary
tree
– Analysis of
delete_max_heap
• The complexity of the
insertion function
is O(log2 n)
parent = 41
2
*n= 5
4
child = 8
2 [1]
4
<
15
20
[2] [3]
15
14 2
[4] [5]
item.key = 20
10 10
14 temp.key = 10
BINARY SEARCH TREES
Binary Search Trees (1)
• Why do binary search trees need?
– Heap is not suited for applications in which arbitrary
elements are to be deleted from the element list
• A min (max) element is deleted O(log2n)
• Deletion of an arbitrary element O(n)
• Search for an arbitrary element O(n)
• Definition of binary search tree
– Every element has a unique key
– The keys in a nonempty left subtree (right subtree) are
smaller (larger) than the key in the root of subtree
– The left and right subtrees are also binary search trees
Yi-Fen Liu, FCU IECS Data Structures (Ch5) - 61
Binary Search Trees (2)
• Example: (b) and (c) are binary search trees
medium
smaller larger
Data Structures (Ch5) - 62
Binary Search Trees (3)
Search(25) Search(76)
• Search
44
17 88
32 65 97
28 54 82
29 76
80
Data Structures (Ch5) - 63
Binary Search Trees (4)
• Searching a binary search tree
Yi-Fen Liu, FCU IECS Data Structures (Ch5) - 64
Binary Search Trees (5)
O(h)
Yi-Fen Liu, FCU IECS Data Structures (Ch5) - 65
Binary Search Trees (6)
• Inserting into a binary search tree
An empty tree
Binary Search Trees (7)
• Deletion from a binary search tree
– Three cases should be considered
– case 1. leaf delete
– case 2.
one child delete and change the pointer to this child
– case 3. two child
either the smallest
element in the right
subtree or the
largest element in
the left subtree
Binary Search Trees (8)
• Height of a binary search tree
– The height of a binary search tree with n elements can
become as large as n
– It can be shown that when insertions and deletions are
made at random, the height of the binary search tree is
O(log2n) on the average
– Search trees with a worst-case height of O(log2n) are called
balance search trees
Yi-Fen Liu, FCU IECS Data Structures (Ch5) - 68
Binary Search Trees (9)
• Time Complexity
– Searching, insertion, removal
• O(h), where h is the height of the tree
– Worst case - skewed binary tree
• O(n), where n is the # of internal nodes
• Prevent worst case
– Rebalancing scheme
– AVL, 2-3, and Red-black tree
Yi-Fen Liu, FCU IECS Data Structures (Ch5) - 69
SELECTION TREES
Selection Trees (1)
• Problem
– Suppose we have k order sequences, called runs, that are
to be merged into a single ordered sequence
• Solution
– Straightforward : k-1 comparison
– Selection tree : log2k+1
• There are two kinds of selection trees
– Winner trees
– Loser trees
Yi-Fen Liu, FCU IECS Data Structures (Ch5) - 71
Selection Trees (2)
• Definition (Winner tree)
– A selection tree is the binary tree where each node
represents the smaller of its two children
– Root node is the smallest node in the tree
• A winner is the record with smaller key
• Rules
– Tournament : between sibling nodes
– put X in the parent node X tree
where X = winner or loser
Yi-Fen Liu, FCU IECS Data Structures (Ch5) - 72
Selection Trees (3)
sequential allocation Each node represents
scheme the smaller of its two
(complete binary tree) children
Winner Tree
ordered sequence
Selection Trees (4)
• Analysis of merging runs using winner trees (k is the
number of sequence)
– # of levels: log2K +1 restructure time: O(log2K)
– Merge time: O(nlog2K)
– Setup time: O(K)
• Slight modification: tree of loser
– Consider the parent node only (v.s. sibling nodes)
Yi-Fen Liu, FCU IECS Data Structures (Ch5) - 74
Selection Trees (5)
6
15
Selection Trees (6)
0
6 8
Tree of losers
can be conducted
by Winner tree 9 17
10 20 9 90
Selection Trees (7)
• The loser tree after output 6
0
8 Overall
winner
1
9
2 3
15 17
4 5 7
6
10 20 9 90
9 10 11 12 13 14 15
10 9 20 15 8 9 90 17
run 1 2 3 4 5 6 7 8
FORESTS
Forests
• Definition
– A forest is a set of n ≥ 0 disjoint trees
• When we remove a root from a tree, we’ll get a
forest
– Removing the root of a binary tree will get a forest of two
trees
A E G
B C D F H I
Three-tree forest
Data Structures (Ch5) - 79
Transforming A Forest Into
A Binary Tree (1)
• T1, …, Tn
– Forest of trees
• B(T1, …, Tn)
– Binary tree
• Algorithm
– Is empty if n = 0
– Has root equal to root(T1)
– Has left subtree equal to B(T11, …, T1m)
• T11, …, T1m are the subtree of root(T1)
– Has right subtree equal to B(T2, …, Tn)
Yi-Fen Liu, FCU IECS Data Structures (Ch5) - 80
Transforming A Forest Into
A Binary Tree (2)
A
A
B C D
B E
E C F G
G
D H
F H I
Data Structures (Ch5) - 81
I
SET REPRESENTATION
UNION & FIND
Set Representation
• Trees can be used to represent sets
• Disjoint set Union
– If Si and Sj are two disjoint sets, then their union
Si ∪Sj = {all elements x such that x is in Si or Sj}.
• Find (i)
– Find the set containing element i
Yi-Fen Liu, FCU IECS Data Structures (Ch5) - 83
Possible Tree
Representation of Sets
Set 2 = {4 , 1 ,9}
S1 S2 S3
0 4 2
6 7 8 1 9 3 5
Set I = {0 , 6 ,7 ,8 } Set 3 = {2 , 3 , 5}
Link the nodes from the children to the parent
Data Structures (Ch5) - 84
Unions of Sets
• To obtain the union of two sets, just set the parent
field of one of the roots to the other root
• To figure out which set an element is belonged to,
just follow its parent link to the root and then follow
the pointer in the root to the set name
Yi-Fen Liu, FCU IECS Data Structures (Ch5) - 85
Possible Representations of S1 ∪S2
S1 S2
0 4
S2
6 7 8 4 1 9
1 9
Yi-Fen Liu, FCU IECS Data Structures (Ch5) - 86
Possible Representations of S1∪S2
S1 S2
0 4
S1
6 7 8 0 1 9
6 7 8
Yi-Fen Liu, FCU IECS Data Structures (Ch5) - 87
Data Representation for S1, S2, S3
Set
Pointer 0 4 2
Name
S1
S2 6 7 8 1 9 3 5
S3
Yi-Fen Liu, FCU IECS Data Structures (Ch5) - 88
Array Representation (1)
• We could use an array for the set name. Or the set
name can be an element at the root.
• Assume set elements are numbered 0 through n-1
i [0] [1] [2] [3] [4] [5] [6] [7] [8] [9]
parent -1 4 -1 2 -1 2 0 0 0 4
Root
Yi-Fen Liu, FCU IECS Data Structures (Ch5) - 89
Array Representation (2)
void Union1( int i , int j )
{
parent[i] = j ;
}
EX: S1 ∪ S2 Union1( 0 , 2 ) ;
i [0] [1] [2] [3] [4] [5] [6] [7] [8] [9]
parent -1
2 4 -1 2 -1 2 0 0 0 4
EX: Find1( 5 ) ;
int Find1( int i )
i =2
{
for(;parent[i] >= 0 ; i = parent[i]) ;
return i ;
} Data Structures (Ch5) - 90
Analysis Union/Find Operations
• For a set of n elements each in a set of its own, then
the result of the union function is a degenerate tree
• The time complexity of the following union-find
operation is O(n2) n-1
• The complexity can be improved by using
weighting rule for union n-2
union(0, 1), find(0) Union operation
union(1, 2), find(0) O(n)
Find operation
Data Structures (Ch5) - 91
union(n-2, n-1), find(0) O(n2) 0
Weighting Rule
• Definition : Weighting rule for union(i, j)
– If the number of nodes in the tree with root i is less
than the number in the tree with root j, then make j
the parent of i; otherwise make i the parent of j
# of nodes in i < #of nodes in j # of nodes in i >= #of nodes in j
j i
i j
Data Structures (Ch5) - 92
i [0] [1] [2] [3] [4] [5] [6] [7] [8] [9]
0 -1
-2 -1
parent-1
-3 0 -1 -1 -1 -1 -1 -1 -1
void union2 (int i, int j) unoin2 (0 , 1 )
{ unoin2 (0 , 2 )
int temp = parent[i] + parent[j]; unoin2 (0 , 3 )
if ( parent[i]>parent[j]) {
parent[i]=j;
parent[j]=temp; temp = -2
} temp = -3
else {
parent[j]=i;
parent[i]=temp;
}
0 1 2 3 n-1
}
11 1
2 23
EX: unoin2 (0 , 1 ) , unoin2 (0 , 2 ) , unoin2 (0 , 2 )
Data Structures (Ch5) - 93
Weighted Union
• Assume we start with a forest of trees, each
having one node
– Lemma: Let T be a tree with n nodes created as a
result of WeightedUnion. No node in T has level
greater than log 2 n 1
• For the processing of an intermixed sequence
of u – 1 unions and f find operations, the time
complexity is O(u + f*log u)
Yi-Fen Liu, FCU IECS Data Structures (Ch5) - 94
Trees Achieving Worst-Case Bound
[-1] [-1] [-1] [-1] [-1] [-1] [-1] [-1]
0 1 2 3 4 5 6 7
(a) Initial height
trees
[-2] [-2] [-2] [-2]
0 2 4 6
1 3 5 7
(b) Height-2 trees following union (0, 1), (2, 3),
(4, 5), and (6, 7)
Data Structures (Ch5) - 95
Trees Achieving Worst-Case Bound
(Cont.)
[-4] [-4] [-8]
0 4 0
1 2 5 6 1 2 4
3 7 3 5 6
(c) Height-3 trees following 7
union (0, 2), (4, 6)
(d) Height-4 trees following
union (0, 4)
Data Structures (Ch5) - 96
Collapsing Rule (1)
• Definition : Collapsing rule
root(i)
– If j is a node on the path from i to its
root and parent[i] ≠ root(i), then set
parent[j] to root(i)
• The first run of find operation will j
collapse the tree. Therefore, all
following find operation of the
same element only goes up one
link to find the root
i
Data Structures (Ch5) - 97
Collapsing Rule (2)
int find2(int i)
{ Ex: find2 (7)
int root, trail, lead;
for (root=i; parent[root]>=0; root=parent[root]);
for (trail=i; trail!=root; trail=lead) {
lead = parent[trail];
parent[trail]= root;
} [-8]
return root: 0
} Root
6 7 1 2 4
Trail
3 5 6
Lead
Data Structures (Ch5) - 98
7
Collapsing Rule (3)
• Analysis of WeightedUnion and CollapsingFind
– The use of collapsing rule roughly double the time
for an individual find. However, it reduces the
worst-case time over a sequence of finds
Yi-Fen Liu, FCU IECS Data Structures (Ch5) - 99
Revisit Equivalence Class
• The aforementioned techniques can be applied to
the equivalence class problem
• Assume initially all n polygons are in an equivalence
class of their own: parent[i] = -1, 0 ≤ i < n.
– Firstly, we must determine the sets that contains i and j
– If the two are in different set, then the two sets are to be
replaced by their union
– If the two are in the same set, then nothing need to be
done since they are already in the equivalence class
– So we need to perform two finds and at most one union.
Yi-Fen Liu, FCU IECS Data Structures (Ch5) - 100
Example (1)
[-1] [-1] [-1] [-1] [-1] [-1] [-1] [-1] [-1] [-1] [-1] [-1]
0 1 2 3 4 5 6 7 8 9 10 11
(a) Initial trees
[-2] [-2] [-2] [-2] [-1] [-1] [-1] [-1]
0 3 6 8 2 5 7 11
4 1 10 9
(b) Height-2 trees following 0≡4, 3≡1, 6≡10, and 8≡9
Data Structures (Ch5) - 101
Example (2)
[-2] [-2] [-2] [-2] [-1] [-1] [-1] [-1]
0 3 6 8 2 5 7 11
4 1 10 9
(b) Height-2 trees following 0≡4, 3≡1, 6≡10, and 8≡9
[-3] [-4] [-3] [-2]
0 6 3 2
4 7 10 8 1 5 11
9
(c) Tree following 7≡4, 6≡8, 3≡5, and 2≡11
Example (3)
[-3] [-4] [-3]
0 6 3
4 7 2 10 8 1 5
11 9
(d) Tree following 11≡0
Data Structures (Ch5) - 103
Counting Binary Tree
• We consider the following three disparate problems
– Determine the number of distinct binary trees having n
nodes
– Determine the number of distinct permutations of the
numbers from 1 through n obtainable by a stack
– Determine the number of distinct ways of multiplying n+1
matrices .
• They amazingly have the same solution
Yi-Fen Liu, FCU IECS Data Structures (Ch5) - 104
Distinct Binary Trees
There are 5 distinct binary tree
Data Structures (Ch5) - 105
Stack permutation (1)
• In section 5.3 we introduced preorder, inorder, and
postorder traversal of a binary tree and indicated
that each traversal requires a stack
• Every binary tree has a unique pair of
preorder/inorder sequences
• The number of distinct binary trees is equal to the
number of inorder permutations obtainable from
binary trees having the preorder permutation, 1 ,
2,…,n.
Yi-Fen Liu, FCU IECS Data Structures (Ch5) - 106
Stack permutation (2)
A preorder: A B C D E F G H I
inorder: B C A E D G H F I
B, C E, D, G, H, F, I
preorder: A B C (D E F G H I)
inorder: B C A (E D G H F I)
A
B D
C E F, G, H, I
Stack permutation (3)
• The number of distinct permutations obtainable by
passing the numbers 1 through n through a stack is
equal to the number of distinct binary trees with n
nodes
• Example
– If we start with the numbers 1 , 2 , and 3 , then the
possible permutations obtainable by a stack are
(1,2,3) (1,3,2) (2,1,3) (2,3,1) (3,2,1)
Yi-Fen Liu, FCU IECS Data Structures (Ch5) - 108
Stack permutation (4)
1 1 1 1 1
2 2 2 3 2 2
3 3 3 3
(1, 2, 3) (1, 3, 2) (2, 1, 3) (2, 3, 1) (3, 2, 1)
Binary trees corresponding to five permutation
Data Structures (Ch5) - 109
Matrix Multiplication (1)
• The number of distinct binary trees is equal to the number of
distinct inorder permutations obtainable from binary trees
having the preorder permutation, 1, 2, …, n.
• Computing the product of n matrices are related to the
distinct binary tree problem
M1 * M 2 * … * Mn
n = 3 (M1 * M2) * M3 M1 * (M2 * M3 )
n = 4 ((M1 * M2) * M3) * M4
(M1 * (M2 * M3)) * M4
M1 * ((M2 * M3) * M4 )
(M1 * (M2 * (M3 * M4 )))
((M1 * M2) * (M3 * M4 ))
Yi-Fen Liu, FCU IECS Data Structures (Ch5) - 110
Matrix Multiplication (2)
• Let bn be the number of different ways to compute
the product of n matrices
– b2 = 1, b3 = 2, and b4 = 5
n 1
bn bi bni , n 1
i 1
Yi-Fen Liu, FCU IECS Data Structures (Ch5) - 111
Number of Distinct Binary Trees (1)
• The number of distinct binary trees of n nodes is
bn
bi bn-i-1
Data Structures (Ch5) - 112
Number of Distinct Binary Trees (2)
B( x) bi x i
• Assume we let i 0
which is the generating
function for the number of binary trees.
• By the recurrence relation we get xB ( x) B( x) 1
2
Yi-Fen Liu, FCU IECS Data Structures (Ch5) - 113