Transcript Trees

•1
Introduction
Def) a tree is finite set of one or more nodes such that
1) there is a special node (root)
2) remaining nodes are partitioned into n  0
disjoint trees T1,T2,···,Tn where each of these is a
tree; we call each Ti subtree of the root
 acyclic
graph : contain no cycle
 hierarchical structure
•2
Level
1
A
B
E
K
C
F
L
G
2
D
H
M
I
J
3
4
•3

Terminology
 Degree
of a node: the number of subtrees of
node
 Degree of a tree: the maximum degree of the
nodes in the tree
 Leaf (terminal) node: a node with degree zero
 Internal (non-terminal) node: node with degree
one or more
 parent: a node that has subtrees
 child: a root of the subtrees
•4

Terminology (cont’d)
sibling: child nodes of the same parent
 ancestor: all the nodes along the path from the
root to the node
 descendant: all the nodes that are in its subtrees
 level: level of node’s parent + 1 (level of the root
node is 1)
 depth (or height) of a tree: the maximum level of
any node in the tree

•5

Representation of trees
 list
representation
 the information in the root node comes first
 followed by a list of the subtrees of that node
 (eg) (A(B(E(K,L),F),C(G),D(H(M),I,J)))
 representation
of a tree in memory where n is
the degree of the tree
data
link 1
link 2
···
link n
•6

Representation of trees
 left-child
right-sibling representation
 left-child
right-sibling
node structure
data
 nodes of a fixed size
 easier to work
 two link / pointer fields per node
left child
right sibling
•7
A
B
E
K
C
F
L
G
D
H
I
J
M
left-child right-sibling representation of a tree
•8

Representation of trees
 representation
as a degree two tree
 simply rotate the left-child right-sibling tree
clockwise by 45 degrees
 two children: left child and right child
 degree 2
 binary tree
•9
A
B
E
K
C
F
G
L
D
H
M
left-child right-child tree representation of a tree
I
J
•10
A
A
B
A
B
tree
B
left child-right sibling tree
A
binary tree
A
A
B
B
C
tree

B
C
left child-right sibling tree
C
binary tree
tree representations
•11
•12
Def) Binary tree is a finite set of nodes such that
1) empty or
2) consists of root node and two disjoint binary
trees, called, left subtree and right subtree
A
B
A
B
two different binary trees
•13

Properties of binary trees
 Difference
between a binary tree and a tree
 may have empty node
 the order of subtree are important
 a binary tree is not a subset of a tree
 maximum number of nodes in a BT: 2k-1 where k:
depth of the tree
 relationship between the number of leaf nodes(n0)
and the number of nodes with degree 2(n2) : n0 =
n2 + 1
•14

Special types of binary trees
 Skewed
 Full
binary tree
binary tree (of depth k)
 a binary tree of depth k(0) having 2k - 1 nodes
 Complete
binary tree
 a binary tree with n nodes that correspond to the
nodes numbered from 1 to n in the full binary tree of
depth k
•15
1
2
3
4
8
5
9
10
6
11
12
7
13
14
15
Full binary tree of depth 4 with sequential node numbers
•16
A
A
B
B
C
C
D
D
H
E
skewed binary tree
E
F
G
I
complete binary tree
skewed and complete binary trees
•17

Binary tree representation
 Array
representation
 Sequential representations
 Determine the locations of the parent, left child, and
right child of any node i in the binary tree
1) parent(i) is at i/2 if i  1. if i = 1, no parent
2) left_child(i) is at 2·i if 2in
3) right_child(i) is at 2·i + 1 if 2·i + 1  n
•18
[1]
A
[2]
B
[3]
-
[1]
A
[4]
C
[2]
B
[5]
-
[3]
C
[6]
-
[4]
D
[7]
-
[5]
E
[8]
D
[6]
F
[9]
-
[7]
G
·
·
[8]
H
·
·
[9]
I
·
·
[16]
E
skew binary tree
complete binary tree
Array representation of binary trees
•19

Problems of array representation
 inefficient
storage utilization
 S(n) = 2k-1, where k: depth of binary tree
 ideal
for complete binary trees
 hard to insert/delete
•20

Linked representation

each node has three fields
 left_child, data, and right_child
typedef struct node *tree_ptr;
typedef struct node {
int data;
tree_ptr left_child, right_child;
};
data
left_child
data
right_child
Node representation for binary trees
left_child
right_child
•21
root
A
NULL
root
B
A
NULL
B
C
NULL
D
D
C
NULL E NULL NULL F NULL NULL G NULL
NULL
NULL H NULL NULL I NULL
NULL E
NULL
skewed binary tree
complete binary tree
Linked representation for the binary trees
•22
 Leaf
node’s link fields contain null pointer
NULL data
NULL
leaf node
 Add
a fourth field, parent, to know the parent of
random nodes
parent
parent
left_child data right_child
data
left_child
right_child
•23

Tree representation
 each
node(in a tree) has variable sized nodes
 hard to represent it by using array
 use linked list
 need k link fields per node where k: degree of
tree
 two types of link: non-null links and null links
 number of non-null links: n-1 (n: # of nodes)
 number of null links: n·k - (n-1)
•24

Convert a tree into a binary tree
1) (parent,chilc1,child2,...,childk) 
(parent,leftmost-child,next-right-sibling)
 left-child right-sibling representation
2) simply rotate the left-child right-sibling tree
clockwise by 45 degrees
- right field of root node always have null link
- null links: approximately 50%
- depth increased
•25
A
B
E
C
F
D
B
G
tree
E
A
B
A
C
C
F
D
D
G
binary tree
E
F
G
left child-right sibling tree
•26
•27
 Visit
each node in the tree exactly once
 produce a linear order for the information in a tree
 what order?
 inorder: LVR (Left Visit Right)
 preorder: VLR (Visit Left Right)
 postorder: LRV (Left Right Visit)
 Note:
 correspondence between these traversals and producing
the infix, postfix, and prefix forms of expressions
•28
1
A / B * C * D + E (infix form)
2
3
4
5
6
7
14
*
/
A
9
17
*
11
8
+
12
15
E
18
19
D
16
C
13
B
10
Binary tree with arithmetic expression
•29

Inorder traversal
void inorder(tree_ptr ptr) {
if(ptr) {
inorder(ptr->left_child);
printf(“%d”,ptr->data);
inorder(ptr->right_child);
}
}
 inorder
is invoked 19 times for the complete
traversal: 19 nodes
 output: A/B*C*D+E
 corresponds to the infix form
•30
call of value in
inorder
root
1
2
3
4
5
6
5
7
4
8
9
8
10
3

+
*
*
/
A
NULL
A
NULL
/
B
NULL
B
NULL
*
action
printf
printf
printf
printf
call of value in
inorder
root
11
12
11
13
2
14
15
14
16
1
17
18
17
19
C
NULL
C
NULL
*
D
NULL
D
NULL
+
E
NULL
E
NULL
action
printf
printf
printf
printf
printf
trace of inorder
•31
 Preorder
traversal
void preorder(tree_ptr ptr) {
if(ptr) {
printf(“%d”, ptr->data);
preorder(ptr->left_child);
preorder(ptr->right_child);
}
}
 output
in the order: +**/ABCDE
 correspond to the prefix form
•32
 Postorder
traversal
void postorder(tree_ptr ptr) {
if (ptr) {
postorder(ptr->left_child);
postorder(ptr->right_child);
printf(“%d”, ptr->data);
}
}
 output
in the order: AB/C*D*E+
 correspond to the postfix form
•33

Iterative inorder traversal

recursion






call itself directly or indirectly
simple, compact expression: good readability
don’t need to know implementation details
much storage: multiple activations exist internally
slow execution speed
application: factorial, fibonacci number, tree
traversal, binary search, tower of Hanoi, quick sort,
LISP structure
•34
void iter_inorder(tree_ptr node) {
int top = -1;
tree_ptr stack[MAX_STACK_SIZE];
while (1) {
while (node) {
push(&top, node);
node = node->left_child;
}
node = pop(&top);
if (!node) break;
printf(“%d”, node->data);
node = node->right_child;
}
}
Iterative inorder traversal
•35
 Every
node of the tree is placed on and removed
from the stack exactly once
 Time complexity: O(n), where n: the number of
nodes in the tree
 space complexity: stack size O(n), where n: worst
case depth of the tree (case of skewed binary tree)
•36

Level order traversal

traversal by using queue(FIFO)
1
2
3
4
8

5
9
10
6
11
12
7
13 14
15
Output in the order: 123456789•••15 for
previous example: +*E*D/CAB
•37
void level_order(tree_ptr ptr) {
int front = rear = 0;
tree_ptr queue[MAX_QUEUE_SIZE];
if (!ptr) return;
addq(front,&rear,ptr);
while (1) {
}
}
ptr = deleteq(&front, rear);
if (ptr) {
printf(“%d”, ptr->data);
if (ptr->left_child)
addq(front,&rear,ptr->left_child);
if (ptr->right_child)
addq(front,&rear,ptr->right_child);
}
else break;
•38

Copying binary trees
 modified version of postorder
tree_ptr copy(tree_ptr original) {
tree_ptr temp;
if (original) {
temp = (tree_ptr)malloc(sizeof(node));
if (IS_FULL(temp)) exit(1);
temp->left_child =
copy(original->left_child);
temp->right_child =
copy(original->right_child);
temp->data = original->data;
return temp;
}
return NULL;
}
•39

Testing for equality of binary trees
 modified version of preorder
int equal(tree_ptr first,tree_ptr second)
{
return ((!first && !second) ||
(first && second
&& (first->data == second->data)
&& equal(first->left_child,
second->left_child)
&& equal(first->right_child,
second->right_child));
}
•40
•41
 There
are more null links than actual pointers
in representation of any binary tree
 n+1 null links out of 2n total links
 How
to use the null links?
 replace the null links by pointers, called threads, to
other nodes in the tree
•42

Construct the thread


Assume ptr represents a node
Rules
1) if ptr->left_child is null
 replace the null link with a pointer to the inorder
predecessor of ptr
2) if ptr->right_child is null
 replace the null link with a pointer to the inorder
successor of ptr
•43
A
B
D
H
C
E
F
G
I
Threaded binary tree
•44
 How
to distinguish actual pointers and threads?
 Add two additional field to the node structure
 left_thread and right_thread
 if ptr->left_thread = TRUE
 ptr->left_child contains thread
 if ptr->left_thread = FALSE
 ptr->left_child contains a pointer to the left child
 Same for right_thread
•45
typedef struct threaded_tree *threaded_ptr;
typedef struct threaded_tree {
short int left_thread;
threaded_ptr left_child;
char data;
threaded_ptr right_child;
short int right_thread;
};
left_thread
left_child
data
right_child right_thread
Threaded node structure
•46

Two threads have been left dangling

How to use two dangling links?
 the left child of H
 the right child of G
 add a head(=dummy) node
left_thread
left_child
data
TRUE

right_child right_thread
FALSE
an empty threaded tree
•47
root
f
f
f
t
H t
D f
t
I
t
B
f
t
E
A
t
f
--
f
f
C f
F
t
f
t
t
G t
f: FALSE
t: TRUE
Memory representation of a threaded tree
•48

Inorder traversal of a threaded binary tree
 Find the inorder successor of ptr
 if ptr->right_thread=TRUE, ptr->right_child
 otherwise follow a path of left-child links from the
right-child of ptr until we reach a node with
left_thread=TRUE
 Find
inorder successor without using a stack
•49
Finding the inorder successor of a node
threaded_ptr insucc(threaded_ptr tree) {
threaded_ptr temp;
temp = tree->right_child;
if (!tree->right_thread)
while (!temp->left_thread)
temp = temp->left_child;
return temp;
}
•50

Inorder traversal
 repeated
calls to insucc()
 time: O(n), where n: number of nodes in a
threaded binary tree
void tinorder(threaded_ptr tree) {
threaded_ptr temp = tree;
for (;;) {
temp = insucc(temp);
if (temp = tree) break;
printf(“%3c”, temp->data);
}
}
Inorder traversal of a threaded binary tree
•51

Inserting a node into a threaded binary tree
 Insert child as the right child of parent
1) change parent->right_thread to FALSE
2) set child->left_thread and child->right_thread to
TRUE
3) set child->left_child to point to parent
4) set child->right_child to point to parent->right_child
5) change parent->right_child to point to child
6) if parent has nonempty right child, child becomes the
inorder predecessor of the node that was previously
parent’s inorder successor
•52
void insert_right(threaded_ptr parent,
threaded_ptr child) {
threaded_ptr temp;
child->right_child=parent->right_child;
child->right_thread=parent->right_thread;
child->left_child=parent;
child->left_thread=TRUE;
parent->right_child=child;
parent->right_thread=FALSE;
if(!child->right_thread) {
temp=insucc(child);
temp->left_child=child;
}
}
Right insertion in a threaded binary tree
•53
root
root
A
A
B
C
before
B
parent
D
child
parent
C
D
child
after
•54
root
root
A
A
parent
B
C
parent
B
D
E
child
before
C
child
X
F
D
X
E
F
after
•55
•56
Def) max(min) tree: a tree in which the key value
in each node is no smaller(larger) than the key
value in its children (if any)
Def) max(min) heap: a complete binary tree that
is also a max(min) tree
 The
root of a max(min) tree contains the
largest(smallest) key in the tree
•57

Representation of max(min) heaps
 Array
representation
 because heap is a complete binary tree
 simple addressing scheme for parent, left(right)
child
•58

Heap structure
#define MAX_ELEMENTS 200
#define HEAP_FULL(n) (n == MaX_ELEMENTS - 1)
#define HEAP_EMPTY(n) (!n)
typedef struct {
int key;
/* other field */
} element;
element heap[MAX_ELEMENTS];
int n = 0;
•59
[1]
[2]
[3]
12
[4]
[5]
10
[1]
[2]
6
14
7
[6]
8
6
[1]
9
[3]
[2]
3
30
25
[4]
5
sample max heaps
•60
[1]
[2]
[5]
10
[2]
20
[3]
7
[4]
[1]
2
4
[6]
8
6
[1]
10
[3]
[2]
83
11
21
[4]
50
sample min heaps
•61

Priority queue
 deletion
 deletes the element with the highest(or the lowest)
priority
 insertion
 insert an element with arbitrary priority into a
priority queue at any time
 (ex)
job scheduling of OS
•62
 We
an use max(min) heap to implement the
priority queues
 possible priority queue representations
representation
insertion
deletion
unordered array
O(1)
O(n)
unordered linked list
O(1)
O(n)
sorted array
O(n)
O(1)
sorted linked list
O(n)
O(1)
max heap
O(log2n)
O(log2n)
•63

Insertion into a max heap
 need
to go from a node to its parent
 linked representation
 add a parent field to each node
 array representation
 a heap is a complete binary tree
 simple addressing scheme
•64
 Select
the initial location for the node to be
inserted
 bottommost-rightmost leaf node
 Insert a new key value
 Adjust key value from leaf to root
 parent position: i/2
 Time
complexity : O(depth of tree)
 O(log2n)
•65
[1]
[2]
[4]
[1]
20
[3]
15
[5]
14
[4]
10
[1]
[4]
14
10
10
(b) initial location of new node
[2]
5
[6]
[4]
2
(c) insert 5 into heap (a)
2
[6]
[1]
[3]
[5]
[5]
20
15
[3]
15
14
(a) heap before insertion
[2]
[2]
2
20
[3]
15
[5]
14
21
20
[6]
10
6
(d) inset 21 into heap (a)
•66
void insert_max_heap(element item, int *n) {
int i;
if (HEAP_FULL(*n)) {
fprintf(stderr,”The heap is full. \n”);
exit(1);
}
i = ++(*n);
while ((i!=1 )&& (item.key > heap[i/2].key)) {
heap[i] = heap[i/2];
i /= 2;
}
heap[i] = item;
}
Insertion into a max heap
•67

Deletion from a max heap
Always delete an element from the root of the
heap
 Restructure the tree so that it corresponds to a
complete binary tree
 Place the last node to the root and from the root
compare the parent node with its children and
exchanging out-of-order elements until the heap
is reestablished
 Time complexity : O(depth of tree)  O(log n)
2

•68
[1]
[2]
[4]
20
[3]
15
[2]
2
[5]
14
20
removed
[1]
[4]
10
[3]
15
2
[5]
14
(a) heap structure
[1]
[2]
15
[1]
10
[3]
[2]
2
[4]
14
15
[3]
2
[4]
14
(b) 10 inserted at the root
10
(c) final heap
•69
element delete_max_heap(int *n) {
element item, temp;
if (HEAP_EMPTY(*n)) {
fprintf(stderr,”The heap is empty\n”);
exit(1);
}
item = heap[1];
temp = heap[(*n)--];
parent = 1; child = 2;
while (child <= *n) {
/* compare left and right child’s key values */
if ((child < *n) && (heap[child].key <
heap[child+1].key))
child++;
if (temp.key >= heap[child].key) break;
/* move to the next lower level */
heap[parent] = heap[child];
parent = child;
child *= 2;
}
heap[parent] = temp;
return item;
}
•70
•71
 Binary
search tree(BST) is a binary tree that is
empty or each node satisfies the following
properties:
1) every element has a key, and no two elements have
the same key
2) the keys in a nonempty left subtree must be smaller
than the key in the root of the subtree
3) the keys in a nonempty right subtree must be larger
than the key in the root of the subtree
4) the left and right subtrees are also BST
•72
20
15
12
25
10
30
5
(a) not a BST
22
60
40
2
70
65
(b) BST
80
(c) BST
•73
 Searching,
insertion, deletion is bounded by O(h)
where h is the height of the BST
 Can perform these operations both
 by key value
eg) delete the element whith key x
 by rank
eg) delete the fifth smallest element
 inorder
traversal of BST
 generate a sorted list
•74

Searching a BST
tree_ptr search(tree_ptr root, int key) {
/*
return a pointer to the node that contains
key. If there is no such node, return NULL
*/
if (!root) return NULL;
if (key == root->data) return root;
if (key < root->data)
return search(root->left_child, key);
return search(root->right_child, key);
}
Recursive search of a BST
•75
tree_ptr iter_search(tree_ptr tree, int key) {
while (tree) {
if (key == tree->data) return tree;
if (key < tree->data)
tree = tree->left_child;
else
tree = tree->right_child;
}
return NULL;
}
Iterative search of a BST
•76
 Time
complexity for searching
 average case: O(h), where h is the height of BST
 worst case: O(n) for skewed binary tree
•77
 Inserting
into a BST
is slightly modified version of
function iter_search
 Modified_search
 return NULL, if the tree is empty or num is present
 otherwise, return a pointer to the last node of the
tree that was encountered during the search
 time complexity for inserting
 O(h) where h is the height of the tree
•78

Inserting into a BST
void insert_node(tree_ptr *node, int num) {
tree_ptr ptr, temp = modified_search(*node, num);
if (temp || !(*node)) {
ptr = (tree_ptr)malloc(sizeof(node));
if (IS_FULL(ptr)) {
fprintf(stderr,”The momory is full\n”);
exit(1);
}
ptr->data = num;
ptr->left_child = ptr->right_child = NULL;
if (*node)
if (num < temp->data)
temp->left_child = ptr;
else
temp->right_child = ptr;
else *node=ptr;
}
}
•79
30
5
40
2
30
5
2
30
40
5
80
2
(a) insert 80
40
35
80
(b) insert 35
Inserting into a BST
•80

Deleting from a BST
 deletion
of a leaf node
 deletion of a node with 1 child
 deletion of a node with 2 children
 time
complexity for deleting
 O(h) where h is the height of the tree
•81

Deleting a leaf or a node with 1 child
30
5
2
40
35
80
30
5
30
40
2
5
80
(a) delete 35 (leaf)
80
2
(b) delete 40 (node with single child)
•82

Deletion of a node with two children
40
40
20
10
60
30
50
45
20
70
55
10
55
30
50
45
70
52
52
(a) tree before deletion of 60
(b) tree after deletion of 60
•83

Height of a BST
 height
of a BST with n elements
 average case: O(log2n)
 worst case: O(n)
eg) use insert_node to insert the keys 1, 2, 3, ..., n into
an initially empty BST
•84

Balanced search trees
 worst
case height: O(log2n)
 searching, insertion, deletion is bounded by
O(h), where h is the height of a binary tree
 AVL tree, 2-3 tree, red-black tree
•85
•86


Merge k ordered sequence(=run) into a single
ordered sequence
 run: ordered sequence consists of some number
of records in non-decreasing order of a key field
selection tree
 each node represent the smaller of its two
children
 the root node represents the smallest node in
the tree
 leaf node represents the first record in the
corresponding run
 compared to the playing of a tournament in
which the winner is the record with the smaller
key
•87
1
2
4
8
6
8
9
6
9
6
10
5
6
11
12
3
8
17
13
14
10
9
20
6
8
9
90
15
16
20
38
20
30
15
25
15
50
11
16
100
110
run 1
run 2 run 3
run 4 run 5
run 6 run 7
7
15
17
18
20
run 8
selection tree for k = 8 showing the first three keys in each of the eight runs
•88
1
: node that is changed
2
4
8
9
8
9
15
9
10
5
6
11
10
9
20
15
16
20
38
20
30
run 1
8
run 2 run 3
12
15
25
25
3
8
17
13
14
8
9
90
15
50
11
16
100
110
run 4 run 5
run 6 run 7
7
15
17
18
20
run 8
selection tree after one record has been output and the tree restructured
•89
 Time
to set up the selection tree the first time is
O(k)
 Time to restructure the tree is O(log k), where
2
k is the number of runs
 Time to merge all n records is O(n·log k)
2
 total time: O(n·log2k)
•90

tree of losers: a tournament tree in which each
non-leaf node retains a pointer to the loser
 slightly faster merging is possible
0
1
2
4
8
10
run 1
8
17
20
10
9
6
9
10
9
overall
winner
5
6
11
20
run 2 run 3
12
6
9
90
13
8
run 4 run 5
3
14
9
90
run 6 run 7
7
15
17
run 8
•91
•92
Def) A forest is a set of n  0 disjoint trees

Removing the root of any tree produce a forest
A
B
C
E
D
F
G
H
I
Forest with three trees
•93

Transforming a forest into a binary tree
1) obtain the binary tree representation for
each of the trees in the forest
2) link all the binary trees together through
sibling field of the root node
A
B
C
E
D
F
G
H
I
•94
Def) If T1,···,Tn is a forest of trees, then the binary
tree corresponding to this forest, denoted by
B(T1,···,Tn):
1) is empty, if n = 0
2) has root equal to root (T1);
has left subtree equal to B(T11,T12,···,T1m),
where T11,T12,···,T1m are the subtrees of
root(T1);
and has right subtree B(T2, ···, Tn)
•95
A
B
E
F
C
D
G
H
I
Binary tree representation of forest
•96
 Forest
traversals
 preorder
traversal
1) if F is empty, then return
2) visit the root of the first tree of F
3) traverse the subtrees of the first tree in tree
preorder
4) traverse the remaining trees of F in preorder
 equivalent to the preorder traversal of the
corresponding binary tree
•97
 Forest
traversals
 inorder
traversal
1) If F is empty, then return
2) traverse the subtrees of the first tree in tree
inorder
3) visit the root of the first tree of F
4) traverse the remaining trees of F in inorder
 equivalent to the inorder traversal
of the corresponding binary tree
•98
 Forest
traversals
 postorder
traversal
1) if F is empty, then return
2) traverse the subtrees of the first tree in tree
postorder
3) traverse the remaining trees of F in postorder
4) visit the root of the first tree of F
 not equivalent to the inorder traversal of the
corresponding binary tree
•99

set 표현에 tree를 사용한다.

편의상의 가정들
 set의 element들은 0, 1, 2, … , n-1임
(실제로 이 숫자들은 symbol table의 index일 수 있음)
 set들은 pairwise disjoint 하다.
즉, 서로 다른 두 set 사이에는 공통 element가 없다.

set에서는 node들간의 link가 children으로부터 parent로
연결되도록 사용함
4
0
6

7
s1
8
1
s2
2
9
3
s3
5
set의 기본 연산
 disjoint set union

Si, Sj 의 disjoint set에 대하여 Si ∪ Sj = {Si이나 Sj에 속한 모든
element들}
find(i) : element i를 가진 set을 찾는다.
위의 그림에서 3은 set S3에 속한다. 8은 set S1에 속한다.

Union and Find Operations

Union
 set union을 구현 시 단순히 한 tree를 다른 tree의 subtree로 만든다.
 Si ∪ Sj는 다음의 그림과 같이 두 가지 방식으로 실행될 수 있다.
0
6
7
4
8
0
4
1
S 1∪ S 2
6
9
or
7
1
8
S2∪ S1
9
 set union을 구현 시 set의 root를 찾기 쉽도록 set을 나타내는
tree의 root에 대한 pointer를 유지하고 element가 속한 set의
name을 찾을 수 있도록 각 root가 set name에 대한 pointer를
유지한다.
0
set
name pointer
S1
S2
S3
6
7
8
4
1
9
2
3
5
 표현의 용이를 위해서 set 이름 Si를 무시하고 root에 있는
element로 set를 호칭한다.
S1을 set 0로 호칭한다.
 Tree에 있는 node가 0에서 n-1로 숫자화 되어 있으므로
각 숫자를 index로 사용하여 array로 표현한다.
int parent[MAX_ELEMENTS]
/*MAX_ELEMENTS : element의 최대 개수
i
parent
[0] [1] [2] [3] [4] [5] [6] [7] [8] [9]
-1
4
-1
2
-1
2
0
0
0
4
root node의 parent field값은 -1을 갖는다.

Find
 해당 element부터 시작하여 root에 도달할 때 까지 index를
따라간다.

Program 5.19: Initial attempt at union-find functions
int simpleFind(int i)
{
for ( ; parent[i] >= 0 ; i = parent[i])
;
return i ;
}
void simpleUnion(int i, int j)
{
parent[i] = j ;
}
Analysis
구현은 용이하나 성능이 떨어진다.
Example
{0}{1}{2}{3}, … ,{p}로 이루어진 set에 대하여 다음의 연산을
수행
p
union(0, 1), find(0)
union(1, 2), find(0)
P-1
•••
union(n-2, n-1), find(0)
1
이러한 union연산은 옆의 그림과
같은 tree를 생성하게 되고 find
0
연산의 성능이 떨어진다.

...
degenerate tree
 union
연산은 매회 constant time에 이루어지므로 총 소요 시간은
O(n)임.

find연산은 0에서부터 root까지 거슬러 올라가야 하므로 i번째 연
산에서 단위 연산의 소요 시간은 O(i)임.
n
 따라서 n-1개의 find연산에 대한 소요 시간은  i = O(n2)임.
i=2

Definition
tree i의 node 개수가 tree j의 node 개수보다 적으면 i의 parent를
j로 만들고 그렇지 않은 경우 j의 parent를 i로 만든다.
Example
앞의 Example에 대하여 다음과 같이 실행됨
0
1 ••• n
0
2 ••• n
1
intial
0
1
2
4
•••
3
union(0,3)
0 = find(0)

n
0
1
union(0,1)
0 = find(0)
3
2
•••
n
union(0,2)
0 = find(0)
1
•••
1
2
3
•••
1
union(0,n)
구현의 용이를 위해 모든 tree의 root에 대해 count field를 유지한다.
즉, i가 root node이면 count[i]는 그 tree에 존재하는 node의 개수이다.
여기서는, root의 parent를 count[i]대신 사용한다.

Program 17 : Union function
void WeightedUnion(int i, int j)
{ /* union the sets with roots i and j using the weighting rule.
parent [i] = - (the number of node in tree i) and
parent [j] = - (the number of node in tree j) */
int temp = parent [i] + parent [j] ;
if (parent [i] > parent [j] {
/* the number of node in tree i < the number of node in tree j */
parent [i] = j ; /* make j the new root */
parent [j] = temp ; }
else { parent [j] = i ; /* make i the new root */
parent [i] = temp ; }
}

Analysis
union2, find1의 사용 시 time complexity
1 find time
n-1 union, m find time

(log2n)
(n+m log2n)
Definition
[Collapse Rule]
j가 i에서 root까지의 path상에 있는 node라 하면 j를
root의 child로 만든다.

Program 18은 find 연산에 Collapse Rule을 포함시킨 것이다.
이 function은 각각의 find의 수행에는 두 배 정도의 시간을
소요하지만 find 연산들의 sequence의 수행시 worst case time을
줄여 준다.

Program 18 : Find function
int find2 (int i)
{
/* find the root of the tree containing element i.
Use the collapsing rule to collapse all nodes from i to root */
int root, trail, lead ;
for (root = i ; parent [root] >= 0 ; root = parent [root]) ;
for (trail = i ; trail >= 0 ; trail = lead) {
lead = parent [trail] ;
parent [trail] = root ; }
return root ;
}

다음 문제들의 정답이 동등

n개의 노드를 가진 서로 다른 이진 트리의 수

스택을 이용하여 얻을 수 있는 1에서 n까지의 서로 다른 순열의 수

n+1개의 행렬을 곱하는 서로 다른 방법의 수

Distinct Binary Trees

node 수에 따른 distinct binary tree의 개수는 ?
n : node의 수
n = 0 또는 n = 1
binary tree는 한 개만 존재
n=2
n=3
n=k?
두개의 binary tree
5개의 binary tree

stack permutations

binary tree는 unique한 preorder / inorder sequence pair를
가지고 있다.
Example
preorder sequence
ABCDEFGHI
inorder sequence
BCAEDGHFI
A
A
B
D,E,F,G,H,I
B,C
(a)
D,E,F,G,H,I
C
(b)
A
B
D
C
E
F
G
(c)
I
H
•Constructing a binary tree from its inorder and preorder sequences

distinct binary tree의 개수 ≡ binary tree에서 preorder
permutation < 1, 2, …, n > 에 대하여 얻을 수 있는 distinct inorder
permutation들의 개수

distinct binary tree들의 개수는 stack에 1, … , n을 순서대로 넣고
가능한 모든 방식으로 빼서 얻은 distinct permutation들의 수와
같음을 보일 수 있다.
Example
n=3
1,2,3을 가지고 스택을 이용하여 얻을 수 있는 순열
: ( 1, 2, 3 ) ( 1, 3, 2 ) ( 2, 1, 3 ) ( 2, 3, 1 ) ( 3, 2, 1 )
( 3, 1, 2 ) : impossible

다섯 개의 ( 1, 2, 3 ) ( 1, 3, 2 ) ( 2, 1, 3 ) ( 2, 3, 1 ) ( 3, 2, 1 ) 순열들
은 세 개의 노드를 가진 서로 다른 다섯 개의 이진 트리와 일치함
1
1
2
1
2
3
3
2
1
3
1
2
2
3
3

Matrix Mutiplication
M1 * M2 * … * 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))
•bn = 루트,노드 수가 bi, bn-i-1인 서브트리로 된 이진트리들
n -1
b n   b i b n -i-1 , n  1 그리고b0  1
i 1
•120