0% found this document useful (0 votes)
35 views

Unit 4

This document defines trees and binary trees and discusses their representations and traversals. It begins with defining what a tree is as a finite set with a root node and partitions of subtrees. It then discusses tree terminology like parent, child, sibling, and level. It describes different representations of trees including list representation and left-child right-sibling representation. It defines binary trees and their abstract data type. It discusses properties of binary trees like their maximum number of nodes and relations between leaf nodes and nodes of degree 2. It compares full and complete binary trees and describes sequential and linked representations of binary trees. It concludes with discussing the three tree traversals: inorder, postorder, and preorder.

Uploaded by

Ahmed Ibrahim
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
35 views

Unit 4

This document defines trees and binary trees and discusses their representations and traversals. It begins with defining what a tree is as a finite set with a root node and partitions of subtrees. It then discusses tree terminology like parent, child, sibling, and level. It describes different representations of trees including list representation and left-child right-sibling representation. It defines binary trees and their abstract data type. It discusses properties of binary trees like their maximum number of nodes and relations between leaf nodes and nodes of degree 2. It compares full and complete binary trees and describes sequential and linked representations of binary trees. It concludes with discussing the three tree traversals: inorder, postorder, and preorder.

Uploaded by

Ahmed Ibrahim
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 105

Unit-4

Tree
s
Tree
s Root
Dusty

Honey Brandy
Bear
Brunhilde Terry Coyote Nugget

Gill Tansey Tweed Zoe Crocus Primrose Nous Belle

leaf

2
Definition of Tree
 A treeis a finite set of one or more
nodes such that:
– There is a specially designated node called
the root.
– The remaining nodes are partitioned into n>=0 disjoint
sets T1, ..., Tn, where each of these sets is a tree.
– We call T1, ..., Tn the subtrees of the root.

3
Level and Depth
Level
1. node (13) A
2. leaf (terminal) 3 1 1
3. nonterminal
4. parent B 2 1 C 2 3 D 2
5. children 2 2
6. sibling
E G H I J 3 3
7. degree of a tree (3)
F 0 30
8. ancestor 2 30 3 31 30
9. level of a node
10. height of a tree L M 4
0 K4 0 4 0 4
(4)

4
Terminology
 The degree of a node is the number of
subtrees of the node
– The degree of A is 3; the degree of C is 1.
 The node with degree 0 is a leaf or
terminal node.
 A node that has subtrees is the parent of
the subtrees.
 These subtrees are the children
of the node.
 Children of the same parent are
siblings.
 along the path of
The ancestors from the root
a node to the
are all 5
Representation of Trees

 List Representation
– ( 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 link 1 link 2 ... link n

How many link fields are


needed in such a representation?

6
Left Child - Right Sibling

data
A left child right sibling

B C D

E F G H I J

K L M

7
Binary Trees

 A binary tree is a finite set of nodes that


is either empty or consists of a root and
two disjoint binary trees called the left
subtree and the right subtree.
 Any tree can be transformed into binary
tree.
– by left child and right sibling representation
 The left subtree and the right subtree
are distinguished.
8
A

E C

F G D
K

H
L

M I

*Figure 5.2 Left child-right child tree representation


of a tree
Abstract Data Type Binary_Tree
 structure Binary_Tree (abbreviated BinTree)
 objects: a finite set of nodes either empty or
consisting of a root node, left Binary_Tree, and
right Binary_Tree.
 functions:

for all bt, bt1, bt2  BinTree, item  element


 Bintree Create()::= creates an empty binary tree

 Boolean IsEmpty(bt)::= if (bt==empty binary


tree) return TRUE else return FALSE

10
Abstract Data Type Binary_Tree

 BinTree MakeBT(bt1, item, bt2)::= return a binary


tree whose left subtree is bt1, whose right subtree is
bt2, and whose root node contains the data item
 Bintree Lchild(bt)::= if (IsEmpty(bt)) return error
else return the left subtree of bt
 element Data(bt)::= if (IsEmpty(bt)) return error
else return the data in the root node of bt
 Bintree Rchild(bt)::= if (IsEmpty(bt)) return error
else return the right subtree of bt

11
Samples of Trees
Complete Binary Tree

A A 1 A

B B 2 B C

C
3 D E F G
Skewed Binary Tree
D

4 H I
E 5

12
Maximum Number of Nodes in BT

 The maximum number of nodes on level i of a


binary tree is 2i-1, i>=1.
 The maximum nubmer of nodes in a binary tree
of depth k is 2k-1, k>=1.

Prove by induction.
k 2i 1  2 k 
i 1
pp. 200
1
13
Relations between Number of
Leaf Nodes and Nodes of Degree 2
 For any nonempty binary tree, T, if n0 is the
number of leaf nodes and n2 the number of nodes
of degree 2, then n0=n2+1
proof:
 Let n and B denote the total number of nodes &
branches in T.
 Let n0, n1, n2 represent the nodes with no children,

single child, and two children respectively.


n= n0+n1+n2, n=B+1,
n=B+1=n1+2n2+1,
n1+2n2+1= 14
n0+n1+n2 ==>
Full BT VS Complete BT
 A fullbinary tree of depth k is a binary tree of
k
depth k having 2 -1 nodes, k>=0.
 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. 由上至下,
A A
由左至右編號
B C B C

D E F G D E F G

O
H I H I J K L M N
Complete binary tree Full binary tree of depth
15
Binary Tree Representations

 Ifa complete binary tree with n nodes (depth


= log n + 1) 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.
– left_child(i) ia at 2i if 2i<=n. If 2i>n, then i has no
left child.
– right_child(i) ia at 2i+1 if 2i +1 <=n. If 2i +1 >n,
then i has no right child.
16
[1] A
Sequential Representation [2] B
(1) waste space
[3] C
(2) insertion/deletion problem
[4] D
A [1] A [5] E
[2] B F
[6]
[3] -- G
B [7]
[4] C H
A [8]
[5] -- I
[9]
C [6] --
[7] -- B C
D [8] D
[9] --
. . D E F G
E
[16] E

H I 17
Linked Representation
typedef struct node *tree_pointer;
typedef struct node {
int data;
tree_pointer left_child,
right_child;
};
data
left_child data right_child
left_child right_child

18
Binary Tree Traversals

 Let L, V, and R stand for moving left, visiting


the node, and moving right.
 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, LRV, VLR
– inorder, postorder, preorder
19
Arithmetic Expression Using BT
inorder traversal
A/ B * C* D + E
+ infix expression

* E preorder traversal
+ * * / ABC D
E prefix
* D expression
postorder traversal
/ C AB / C * D* E +
postfix
expression
A B
level order traversal
+*E*D/CAB
20
Inorder Traversal (recursive version)
void inorder(tree_pointer ptr)
/* inorder tree traversal */
{
A/ B* C * D+ E
if (ptr) {
inorder(ptr->left_child);
printf(“%d”, ptr->data);
inorder(ptr->right_child);
}
} 21
Preorder Traversal (recursive
version)
void preorder(tree_pointer ptr)
/* preorder tree traversal */
{
+ * * / ABC D E
if (ptr) {
printf(“%d”, ptr->data);
preorder(ptr->left_child);
preorder(ptr->right_child);
}
} 22
Postorder Traversal (recursive
version)
void postorder(tree_pointer ptr)
/* postorder tree traversal */
{
AB / C* D * E +
if (ptr) {
postorder(ptr->left_child);
postorder(ptr->right_child);
printf(“%d”, ptr->data);
}
} 23
Iterative Inorder Traversal
(using stack)
void iterInorder(tree_pointer node)
{
int top= -1; /* initialize stack */
tree_pointer
stack[MAX_STACK_SIZE]; for (;;) {
for (; node; node=node-
>left_child)
push(&top, node);/* add to stack */
node= pop(&top);
/* delete from stack
*/
if (!node) break; /* empty stack
} */ printf(“%D”, node->data);
node = O(n)
node->right_child; LV
} R
Trace Operations of Inorder Traversal
Call of inorder Value in root Action Call of inorder Value in root Action
1 + 11 C
2 * 12 NULL
3 * 11 C printf
4 / 13 NULL
5 A 2 * printf
6 NULL 14 D
5 A 15 NULL

printf
7 NULL 14 D printf
4 / 16 NULL

printf
8 B 1 + printf
9 NULL 17 E
8 B 18 NULL
25
LV
Level Order Traversal
(using queue)

void levelOrder(tree_pointer ptr)


/* level order tree traversal */
{
int front = rear = 0;
tree_pointer queue[MAX_QUEUE_SIZE];
if (!ptr) return; /* empty queue
*/ addq(ptr);
for (;;) {
ptr = delete();

26
if (ptr) {
printf(“%d”, ptr->data);
if (ptr->left_child)
addq(ptr->left_child);
if (ptr->right_child)
addq(ptr-
>right_child);
}
else break;
}
} +*E*D/CAB

27
Traversing a binary tree
 前序走訪 (preorder):
40 95 65 70 98
40
17

22
17 95

22 65 98

70
Traversing a binary tree
 中序走訪 (inorder):
17 65 70 95 98
40
22

40
17 95

22 65 98

70
Traversing a binary tree
 後序走訪 (postorder):
22 65 98 95 40
40
17

70
17 95

22 65 98

70
Traversing a binaryqueuetree
 階層走訪 (level-order): 17 95 22 65 98 70

40

95 22 65 98 70
40 40 17

17 95

22 65 98

70
Copying Binary Trees
tree_pointer copy(tree_pointer original)
{
tree_pointer temp;
if (original) {
temp=(tree_pointer) malloc(sizeof(node));
if (IS_FULL(temp)) {
fprintf(stderr, “the memory is full\n”);
exit(1);
}
temp->left_child=copy(original->left_child);
temp->right_child=copy(original->right_child);
temp->data=original->data;
return temp;
}
return NULL;
} postorder
32
Equality of Binary Trees
the same topology and data
int equal(tree_pointer first, tree_pointer second)
{
/* function returns FALSE if the binary trees first
and second are not equal, otherwise it returns TRUE
*/
return ((!first && !second) || (first && second &&
(first->data == second->data) &&
equal(first->left_child, second->left_child) &&
equal(first->right_child, second->right_child))
}

33
Propositional Calculus Expression

 A variable is an expression.
 If x and y are expressions, then ¬x,
xy, xy are expressions.
 Parentheses can be used to alter the
normal order of evaluation (¬ >  > ).
 Example: x1  (x2  ¬x3)

 satisfiability
problem: Is there an
assignment to make an expression
true? 34
(x1  ¬x2)  (¬ x1  x3)  ¬x3

(t,t,t) 
(t,t,f)
(t,f,t)  
(t,f,f)
(f,t,t)   X3
(f,t,f)
(f,f,t) X1   X3
(f,f,f)

2n possible combinations X2 X1
for n variables
postorder traversal (postfix evaluation)
LRV
Node Structure
left_child data value right_child

typedef emun {not, and, or, true, false } logical;


typedef struct node *tree_pointer;
typedef struct node {
tree_pointer left_child;
logical data;
short int value;
tree_pointer right_child;
};
First version of satisfiability algorithm
for (all 2n possible combinations)
{ generate the next combination;
replace the variables by their values;
evaluate root by traversing it in postorder;
if (root->value) {
printf(<combination>);
return;
}
}
printf(“No satisfiable
combination \n”);
Post-order-eval function
void postOrderEval(tree_pointer node)
{
/* modified post order traversal to evaluate a propositional
calculus tree */
if (node) {
post_order_eval(node->left_child);
post_order_eval(node->right_child);
switch(node->data) {
case not: node->value
=
!node->right_child->value;
break;
case and: node->value =
node->right_child->value &&
node->left_child->value;
break;
case or: node->value =
node->right_child->value | |
node->left_child->value;
break;
case true: node->value = TRUE;
break;
case false: node->value =
FALSE;
}
}
}
Threaded Binary Trees
 Many null pointers in current
representation of binary trees
n: number of nodes;
total links: 2n
number of non-null links: n-1
null links: 2n-(n-1)=> n+1
 Replace these null pointers with some
useful “threads”.

40
Threaded Binary Trees
(Continued)
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

41
A Threaded Binary Tree
root A
dangling
B C

dangling D E F G

inorder traversal:
H I H, D, I, B, E, A, F, C, G

42
Data Structures for Threaded BT
left_thread left_child data right_child
right_thread
TRUE   FALSE

TRUE: thread FALSE: child


typedef struct threaded_tree
*threaded_pointer;
typedef struct threaded_tree
{ short int left_thread;
threaded_pointer left_child;
char data;
threaded_pointer right_child;
short int right_thread; };
Memory Representation of A Threaded BT

root --
f f

f A f

f B f f C f

f D f t E t t F t t G

t H t t I t

44
Next Node in Threaded BT
threaded_pointer insucc(threaded_pointer
tree)
{
threaded_pointer temp;
temp = tree->right_child;
if (!tree->right_thread)
while (!temp->left_thread)
temp = temp-
>left_child;
return temp;
} 45
Inorder Traversal of Threaded BT

void tinorder(threaded_pointer tree)


{
/* traverse the threaded binary tree
inorder */
threaded_pointer temp = tree;
for (;;) {
temp = insucc(temp);
O(n) if (temp==tree) break;
printf(“%3c”, temp->data);
}
} 46
Inserting Nodes into Threaded BTs
 Insert
child as the right child of node
(parent)
– change parent->right_thread to FALSE
– set child->left_thread and child->right_thread
to TRUE
1. set child->right_child to parent->right_child
2. set child->left_child to point to parent
3. change parent->right_child to point to child

47
Examples
Insert a node D as a right child of B.
empty
root root

A A
(1)
parent parent
B B
(3)
C child C child
D
D (2)
(a)
48
*Figure 5.24: Insertion of child as a right child of parent in a threaded binary
tree
nonempty

(3)

(2) (1)

(4)
Right Insertion in Threaded BTs
void insertRight(threaded_pointer parent,
threaded_pointer child)
{ threaded_pointer temp;
(1)
child->right_child = parent->right_child;
child->right_thread = parent->right_thread;
(2) child->left_child
child->left_thread= =parent;
TRUE; case (a)
(3) parent->right_child = child;
parent->right_thread = FALSE;
if (!child->right_thread) { case (b)
temp = insucc(child);
(4) temp->left_child = child;
}
} 50
Heap
 A max tree is a tree in which the key value in
each node is no smaller than the key values in
its children.
– A max heap is a complete binary tree that is also a
max tree.
 A min tree is a tree in which the key value in
each node is no larger than the key values in
its children.
– A min heap is a complete binary tree that is also
a min tree.
 Operations on heaps
– creation of an empty heap
– insertion of a new element into the heap
– deletion of the largest element from the heap
*Figure 5.25: Max heaps

[1] 9
[1] 14 [1] 30

[3] 7 [2] 6 [3] 3 [2] 25


[2] 12
[4] [6] [4]
[5] 8 6 5
10

Property:
The root of max heap (min heap) contains
the largest (smallest).
*Figure 5.26: Min heaps

[1]
2 [1] 10 [1] 11

[2] 7 [3] 4 [2] 21


[2] 20 [3] 83

[4] [5] [6] [4]


10 8 6 50
structure MaxHeap
ADT for Max Heap
 objects: a complete binary tree of n > 0 elements organized so that
the value in each node is at least as large as those in its children
functions:
for all heap belong to MaxHeap, item belong to Element,
n, max_size belong to integer
 MaxHeap Create(max_size)::= create an empty heap that
can
hold a maximum of max_size
elements
 Boolean HeapFull(heap, n)::= if (n==max_size) return
TRUE
else return FALSE
 MaxHeap Insert(heap, item, n)::= if (!HeapFull(heap,n))
insert
item into heap and return the resulting
heap else return error
 Boolean HeapEmpty(heap, n)::= if (n>0) return FALSE
54
else return TRUE
else return error
Application: priority queue

 Machine service (Example


5.1)
– amount of time (min heap)
– amount of payment (max heap)
 Factory (Example 5.2)
– time tag (min heap)

55
ADT MaxPriorityQuere 是
物件: n 個元素形成的集合 (n > 0) ,每個元素有一個鍵值
函式:對所有的 q∈MaxPriorityQueue , item∈Element , n
是整 數
MaxPriorityQueue ::= 建立一個空的優先權佇列
create(max_size)
Boolean isEmpty(q,n) ::= if(n > 0) return FALSE
else return TRUE
Element top(q,n) ::= if(!isEmpty(q,n)) return q
內 最大的元素
else return 錯誤
Element pop(q,n) ::= if(!isEmpty(q,n)) return q 內
最大的元素並把它從堆積中
移除
else return 錯誤
MaxPriorityQueue ::= 把 item 插入 q 中並回傳優先
push(q,item,n) 權佇列的結果

56
Data Structures

 unordered linked
list
 unordered array

 sorted linked list

 sorted array

 heap

57
*Figure 5.27: Priority queue representations

Representation Insertion Deletion

Unordered (1) (n)


array
Unordered (1) (n)
linked list
Sorted array O(n) (1)
Sorted linked O(n) (1)
list
Max heap O(log2n) O(log2n)
Example of Insertion to Max Heap

20 20 21

15 2 15 5 15 20

14 10 14 10 2 14 10 2

initial location of new node insert 5 into heap insert 21 into heap

59
Insertion into a Max Heap
void push(element item, int *n)
{/* 把項目加入目前大小是 n 的最大堆積
*/
int i;
if (HEAP_FULL(*n)) {
O(log2n)
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]; // moving up to root
i /= 2;
}
heap[i]= item;
2 k-1=n ==> k=log (n+1)
2

}
60
Example of Deletion from Max Heap

remove
20 10 15

15 2 15 2 14 2

14 10 14 10

61
Deletion from a Max Heap
element pop(int *n)
{/* 從堆積中刪除鍵最高的元素
*/ int parent, child;
element item, temp;
if (HEAP_EMPTY(*n)) {
fprintf(stderr, “The heap is empty\n”);
exit(1);
}
/* save value of the element with the
highest key */
item = heap[1];
/* use last element in heap to adjust heap */
temp = heap[(*n)--];
parent = 1;
child = 2; 62
while (child <= *n) {
/* find the larger child of the current
parent */
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];
head = child;
child *= 2;
}
heap[parent] = temp;
return item;
}

63
ADT Dictionary 是
物件: n 個資料對形成的集合 (n > 0) ,每個資料對有一個鍵值和
搭配 的項目
函式:
對於所有的 d∈Dictionary , item∈Item , k∈Key , n 是整數
Dictionary Create(max_size) ::= 建立一個空的字典

Boolean IsEmpty(d,n) ::= if(n>0) return FALSE


else return TRUE
Element Search(d,k) ::= return 鍵值為 k 的項目
return NULL 如果沒有此
元素
Element Delete(d,k) ::= 刪除並回傳 ( 如果有 ) 鍵值
為 k 的項目
void Insert(d,item,k) ::= 把鍵值為 k 的 item 插入 d 中

64
Binary Search Tree
 Heap
– a min (max) element is deleted. O(log2n)
– deletion of an arbitrary element O(n)
– search for an arbitrary element O(n)
 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.
65
Examples of Binary Search Trees

20 30 60

12 25 5 40 70

10 15 22 2 65 80

66
Searching a Binary Search Tree
tree_pointer search(tree_pointer 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);
Another Searching
Algorithm
tree_pointer iterSearch(tree_pointer
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; O(h)
} 68
Insert Node in Binary Search Tree

30 30 30

5 40 5 40 5 40

2 2 80 2 35 80

Insert 80 Insert 35

69
void
Insertion into a Binary Search Tree
insert(tree_pointer *node, int k, iType
theItem)
{tree_pointer ptr,
temp = modified_search(*node, k);
if (temp || !(*node)) {/* k 不在樹中 */
ptr = (tree_pointer)
malloc(sizeof(node));
if (IS_FULL(ptr)) {
fprintf(stderr, “The memory is full\
n”); exit(1);
}
ptr->data.key = k; ptr->data.item =
theItem; ptr->left_child = ptr->right_child
= NULL; if (*node)
if (k < temp->data) temp->left_child=ptr;
else temp->right_child = ptr;
else *node = ptr;
70
}
Binary search tree insert and
search
 用 list 的方式實作 binary search tree 的插
入 和搜尋
 實作步驟
1. 建立樹的 node 結構 (struct)
2. 建立一棵 binary search tree
3. 主要 function
– 插入 : insertNode()
– 搜尋 : searchNode()
Binary search tree insert and
search
 建立一棵 binary search
tree
40

40, 17, 95, 22, 65, 70, 98 17 95

22 65 98

70
Binary search tree insert and
search
 插入 40

20 20 < 40

17 95

20 > 17
22 65 98

20 < 22
20 70
Binary search tree insert and
search
 搜尋 40

70 70 > 40

17 95

70 < 95

22 65 98

70 > 65
20 70
Binary search tree insert and
search
 建立樹的 node 結構
(struct)
Binary search tree insert and
search
 插入 :
insertNode()
Binary search tree insert and
search
 插入 :
insertNode()
Binary search tree insert and
search
 搜尋 :
searchNode()
Deletion for a Binary Search Tree

5 5

5 40 2 40

2 80 80

(a) (b)

79
Deletion for a Binary Search Tree
40 non-leaf 40
node
20 60 20 55

10 30 50 70 10 30 50 70

45 55 45 52

52
Before deleting 60 After deleting 60 In the left, to
find the maximum
In the right, to find the minmum
80
Split a Binary Search Tree
void split (nodePointer *theTree, int k, nodePointer *samll,
element *mid, nodePointer *big)
{ /* 根據鍵 k 來分割二元搜尋樹 */
if (!theTree) {*small = *big = 0; (*mid).key = -1;
return;}
/* 空樹 */
nodePointer sHead, bHead, s, b, currentNode;
/* 替 small 和 big 建立標頭節點 */
MALLOC(sHead, sizeof(*sHead));
MALLOC(bHead, sizeof(*bHead));
s = sHead, b = bHead;
/* 執行分割 */
currentNode = *theTree;
81
while (currentNode)
if (k < currentNode→data.key) { /* 加到 big
*/ b→leftChild = currentNode; b =
currentNode; currentNode =
currentNode→leftChild; }
else if (k > currentNode→data.key) { /* 加到
small */
s→rightChild = currentNode; s = currentNode;
currentNode = currentNode→rightChild; }

else { /* 在 currentNode 做 分 割 */
s→rightChild = currentNode→leftChild;
b→leftChild =
currentNode→rightChild;
*small = sHead→rightChild;
free(sHead);
*big = bHead→leftChild; free(bHead);
82
(*mid).item =
/* 沒有鍵為 k 的字典對 */
s→rightChild = b→leftChild = 0;
*small = sHead→rightChild; free(sHead);
*big = bHead→leftChild; free(bHead);
(*mid).key = -1;
return;
}

83
Selection Trees
(1) Winner tree
(2) Loser tree

84
Each node represents
Sequential allocation
scheme
Winner tree the smaller of its two
1 children.
(complete binary
6
tree)
2 3
6 8
4 5 6 7
9 6 8 17

8 9 10 11 14 15
12 13
10 9 20 6 9 90 17
8
ordered sequence

15 20 20 15 15 11 10 18
16 38 30 25 50 16 0 20
11
0

run 1 run 2 run 3 run 4 run 5 run 6 run 7 run 8


85
*Figure 5.35: Selection tree of Figure 5.34 after one record has been
output and the tree restructured (nodes that were changed are
ticked)
1 
8
2  3
9 8

4 5  6 7
9 15 8 17
8 9 10 11 12 13 14 15
10 9 20 15 8 9 90 17
15 20 20 25 15 11 100 18
16 38 30 25 50 16 110 20
Analysis
 K: # of runs
 n: # of records

 setup time: (K-1)

O(K)
 restructure time: O(log2K) log2(K+1)

 merge time: O(nlog2K)


 slight modification: loser tree
– consider the parent node only (vs. sibling nodes)

87
*Figure 5.34: Tree of losers corresponding to Figure 5.32
overall
6
8 winner
9
1
8

2
9 3
9 15 17

4 5 6 7
10 20 15 9 90

8 9 10 11 12 13 14 15
10 9 20 6 8 9 90 17
Run 1 2 3 4 5 6 7 8
15 15
Forest
 Definition: A forest is a set of n >= 0 disjoint trees

A
Forest
A E G
B E

B C D F H I C F G

D H

89
Transform a forest into a binary tree

 T1, T2, …, Tn: a forest of trees


 B(T1, T2, …, Tn): a binary
tree corresponding to this
forest
 Algorithm
(1) empty, if n = 0
(2) has root equal to root(T1)
has left subtree equal to B(T11,T12,…,T1m)
has right subtree equal to B(T2,T3,…,Tn)
90
Forest Traversals

 Preorder (VLR)
– If F is empty, then return
– Visit the root of the first tree of F
– Taverse the subtrees of the first tree in tree preorder
– Traverse the remaining trees of F in preorder
 Inorder (LVR)
– If F is empty, then return
– Traverse the subtrees of the first tree in tree inorder
– Visit the root of the first tree
– Traverse the remaining trees of F is indorer

91
A inorder: EFBGCHIJDA
preorder:
B ABEFCGDHIJ
A

E C
B C D

F G D
E F J
G H I
H

I
B C
preorder
D
J
E G H
I
F J
92
Set Representation

 S1={0, 6, 7, 8}, S2={1, 4, 9}, S3={2, 3,


5} 0 1 2
Si  Sj = 

6 7 8 4 9 3 5

 Two operations considered here


– Disjoint set union S1 
S2={0,6,7,8,1,4,9}
– Find(i): Find the set containing the element i.
3  S3 , 8  S 1 93
Disjoint Set Union
Make one of the trees a subtree of the other

0 1

8 1 0 4 9
6 7

4 9 6 7 8

Possible representation for S1 union S2


S1  S2
94
*Figure 5.39:Data Representation of S1S2and S3

0
Set Pointer
Name
6 7 8
S1
S2 4

S3 1 9

3 5
Array Representation for Set
i [0] [1] [2] [3] [4] [5] [6] [7] [8] [9]
parent -1 4 -1 2 -1 2 0 0 0 4

int simpleFind(int i)
{
for (; parent[i]>=0; i=parent[i]);
return i;
}
void simpleUnion(int i, int j)
{
parent[i]= j;
}
96
*Figure 5.41:Degenerate tree ( 退化
樹)

union operation n-1 union(0,1), find(0)


O(n) n-1 union(1,2), find(0)
.
find operation n-2 .
O(n2) n .
i union(n-2,n-1), find(0)
i 2 

degenerate tree
*Figure 5.42:Trees obtained using the weighting rule

weighting rule for union(i,j):


if # of nodes in i < # in j then make j the parent of
i
0 1 • • • n-1 0 2 • • n-1 0 3 •• n-1

• •
1 1
起始狀況 2
Union Union
(0,1) (0,2)
0 4 •• n-1 0
• • •
1 2 • 1 2 3 •• n-1

3 •
Union
(0,3) Union (0,n-1)
Modified Union Operation
void weightedUnion(int i, int j)
{ Keep a count in the root of tree
//parent[i]=-count[i] and parent[i]=-count[j]
int temp = parent[i]+ parent[j];
if (parent[i]>parent[j]) {
parent[i]=j;
/* make j the new root*/
parent[j]=temp;
}
else {
parent[j]=i;
/* make i the new root*/
parent[i]=temp;
} If the number of nodes in tree i is
} less than the number in tree j,
then make j the parent of i;
otherwise make i the parent of j.
[-1] [-1] [-1] [-1] [-1] [-1] [-1] [-1]
0 1 2 3 4 5 6 7

(a) 一 開 始 樹 的 高 度 都 是 1

[-2] [-2] [-2] [-2]


0 2 4 6

1 3 5 7

(b) 執 行 Uni on (0,1) , (2,3) , (4,5) ,與 (6,7) 後 樹 之 高 度 為


2
[-4] [-4]
0 4

1 2 5 6

(c) 執 行 U n i o n (0,2) 與 (4,6) 後 樹 之 高 度 為


3

[-8]
1 2 4
0

3 5 6

(d) 執 行 U n i o n (0,4) 後 樹 之 高 度 為 4 Figure 5.43:Trees


collapsingFind(i) Operation
int collapsingFind(int i)
{
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;
}
If j is a node on the path from
return root:
i to its root then make j a child
} of the root
101
0 0

1 2 4 1 2 4 6 7

3 5 6 3 5

find(7) find(7) find(7) find(7) find(7) find(7) find(7) find(7)


go up 3 1 1 1 1 1 1 1
reset 2
13 moves (vs. 24 moves)

102
Application to Equivalence Classes

 Find equivalence class i  j


 Find Si and Sj such that i  Si and j  Sj
(two finds)
– Si = Sj do nothing
– Si  Sj union(Si , Sj)
 example
0  4, 3  1, 6  10, 8  9, 7  4, 6  8,
3  5, 2  11, 11  0
{0, 2, 4, 7, 11}, {1, 3, 5}, {6, 8, 9, 10}
103
[-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) 起 始 樹

[-2] [-2] [-2] [-2] [-1] [-1] [-1] [-1]


0 3 6 8 2 5 7 11

4 1 10 9

(b) 處 理 完 0 ≡ 4, 3 ≡ 1, 6 ≡ 10, 8 ≡ 9 後 高 度 為 2 的

[-3] [-4] [-3] [-2]


0 6 3 2

4 7 10 8 1 5 11

(c) 處 理 完 7 ≡ 4, 6 ≡ 8, 3 ≡ 5,
2 ≡ 11 後 的 樹
[-5] [-4] [-3]
0 6 3

4 7 2 10 8 1 5

11 9

(d) 處 理 完 11 ≡ 0 後 的 樹
preorder: ABCD EFGHI
inorder: BCAEDGHF
A I A

B, C D, E, F, G, H, I B D

A
C E F

B D, E, F, G, H, I G I

C H

105

You might also like