chapter 5. trees - yuynucc.yu.ac.kr/~hrcho/courses/ds/chap5.pdfchap 5: trees(page 1) chapter 5....

38
Chap 5: Trees (Page 1) Chapter 5. TREES 1. INTRODUCTION 2. BINARY TREES 3. BINARY TREE TRAVERSALS 4. ADDITIONAL BINARY TREE OPERATIONS 5. THREADED BINARY TREES 6. HEAPS 7. BINARY SEARCH TREES 8. SELECTION TREES 9. FORESTS 10. SET REPRESENTATION 11. COUNTING BINARY TREES Chap 5: Trees (Page 2) 1. INTRODUCTION Two Types of Genealogical Charts: Figure 5.1 Definition of Tree: A finite set of one or more nodes s.t.: (1) One Specially Designated Node called root (2) Remaining Nodes: partitioned into n 0 disjoint sets, T 1 , ..., T n , where each of T i is a tree. T 1 , ..., T n : Subtrees of root

Upload: others

Post on 21-May-2020

8 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Chapter 5. TREES - YUynucc.yu.ac.kr/~hrcho/Courses/DS/Chap5.pdfChap 5: Trees(Page 1) Chapter 5. TREES 1. INTRODUCTION 2. BINARY TREES 3. BINARY TREE TRAVERSALS 4. ADDITIONAL BINARY

Chap 5: Trees (Page 1)

Chapter 5. TREES

1. INTRODUCTION

2. BINARY TREES

3. BINARY TREE TRAVERSALS

4. ADDITIONAL BINARY TREE OPERATIONS

5. THREADED BINARY TREES

6. HEAPS

7. BINARY SEARCH TREES

8. SELECTION TREES

9. FORESTS

10. SET REPRESENTATION

11. COUNTING BINARY TREES

Chap 5: Trees (Page 2)

1. INTRODUCTION

� Two Types of Genealogical Charts: Figure 5.1

� Definition of Tree: A finite set of one or more nodes s.t.:

(1) One Specially Designated Node called root

(2) Remaining Nodes: partitioned into n ≥ 0 disjoint sets,T1, ..., Tn, where each of Ti is a tree.

T1, ..., Tn : Subtrees of root

Page 2: Chapter 5. TREES - YUynucc.yu.ac.kr/~hrcho/Courses/DS/Chap5.pdfChap 5: Trees(Page 1) Chapter 5. TREES 1. INTRODUCTION 2. BINARY TREES 3. BINARY TREE TRAVERSALS 4. ADDITIONAL BINARY

� A Sample Tree

Chap 5: Trees (Page 3)

A

B C D

E F G H I J

K L M

Level 1

Level 2

Level 3

Level 4

� Terminologies✔ Degree of a node (A: 3), Degree of a tree (3)

✔ Leaf or Terminal Node (K, L, F, G, M, I, J)

✔ Parent (E: B), Children (B: E & F), Siblings (E & F)

✔ Ancestor (M: H, D, A), Descendants (B: E, F, K, L)

✔ Level (Root: 1), Height or Depth (4)

Chap 5: Trees (Page 4)

1.2 Representation of Trees

� List Representations✔ (A (B (E (K, L), F), C (G), D (H (M), I, J)))

✔ Using Linked List: Requires Varying # of Fields

� Left Child - Right Sibling Representation✔ Two Link Fields per Node

Link 1 Link 2 Link n…data

Right childLeft child

data

Page 3: Chapter 5. TREES - YUynucc.yu.ac.kr/~hrcho/Courses/DS/Chap5.pdfChap 5: Trees(Page 1) Chapter 5. TREES 1. INTRODUCTION 2. BINARY TREES 3. BINARY TREE TRAVERSALS 4. ADDITIONAL BINARY

Chap 5: Trees (Page 5)

A

B C D

E F G H I J

K L M

⇒ Binary Tree

Chap 5: Trees (Page 6)

2. BINARY TREES

� The Abstract Data Type

� Properties of Binary Trees� Binary Tree Representations

Page 4: Chapter 5. TREES - YUynucc.yu.ac.kr/~hrcho/Courses/DS/Chap5.pdfChap 5: Trees(Page 1) Chapter 5. TREES 1. INTRODUCTION 2. BINARY TREES 3. BINARY TREE TRAVERSALS 4. ADDITIONAL BINARY

Chap 5: Trees (Page 7)

2.1 The Abstract Data Types

� Chief Characteristics of Binary Tree✔ Degree of Any Node Must Not Exceed 2

✔ Distinguish Between Left Subtree and Right Subtree

✔ Binary Tree May Have Zero Nodes

� Definition of Binary Tree: A finite set of nodes that is either

(1) Empty or

(2) A root with two disjoint binary trees, left/right subtree

Figure 5.9: Skewed and complete binary trees

Chap 5: Trees (Page 8)

Level1

2

3

4

5

A

E

B

C

D

A

B

D

H I

E

C

F G

(a) (b)

Page 5: Chapter 5. TREES - YUynucc.yu.ac.kr/~hrcho/Courses/DS/Chap5.pdfChap 5: Trees(Page 1) Chapter 5. TREES 1. INTRODUCTION 2. BINARY TREES 3. BINARY TREE TRAVERSALS 4. ADDITIONAL BINARY

Structure 5.1: Abstract data type Binary_Tree

Chap 5: Trees (Page 9)

structure Binary_Tree (abbreviated BinTree) is

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 treeBoolean IsEmpty(bt) ::= if (bt == empty binary tree)

return TRUE else return FALSE

BinTree MakeBT(bt1, item, bt2) ::= return a binary tree whose leftsubtree is bt1, whose rightsubtree is bt2, and whose root

node contains the data item.BinTree Lchild(bt) ::= if (IsEmpty(bt)) return error else

return the data in the root node of bt.

BinTree Rchild(bt) ::= if (IsEmpty(bt)) return error elsereturn the right subtree of bt.

Figure 5.8: Two different binary trees

Chap 5: Trees (Page 10)

A

B

A

B

Page 6: Chapter 5. TREES - YUynucc.yu.ac.kr/~hrcho/Courses/DS/Chap5.pdfChap 5: Trees(Page 1) Chapter 5. TREES 1. INTRODUCTION 2. BINARY TREES 3. BINARY TREE TRAVERSALS 4. ADDITIONAL BINARY

Chap 5: Trees (Page 11)

2.2 Properties of Binary Trees

� Lemma 5.1 [Maximum # of nodes]:(1) Maximum # of nodes on level i = 2i-1, i ≥ 1

(2) Maximum # of nodes in a binary tree of depth k =

� Lemma 5.2 [# of leaf nodes vs. # of nodes of degree 2]:n0: # of leaf nodes, n2: # of nodes of degree 2

⇒ n0 = n2 + 1

(Pf) n = n0 + n1 + n2 & n = B + 1 = n1 + 2n2 + 1

� Definition: Full binary tree of depth kA binary tree of depth k having 2k - 1 nodes, k ≥ 0.

∑=

− −=k

i

ki

1

1 122

� Definition: Complete binary tree of depth kA binary tree of which nodes corresponds to the nodes numbered from 1 to n is in the full binary tree of depth k

Chap 5: Trees (Page 12)

1

2 3

5

9 10 118 12 15

6

13

4 7

14

Page 7: Chapter 5. TREES - YUynucc.yu.ac.kr/~hrcho/Courses/DS/Chap5.pdfChap 5: Trees(Page 1) Chapter 5. TREES 1. INTRODUCTION 2. BINARY TREES 3. BINARY TREE TRAVERSALS 4. ADDITIONAL BINARY

Chap 5: Trees (Page 13)

2.3 Binary Tree Representations

� Array RepresentationUse 1-dimensional array by Lemma 5.3

� Lemma 5.3: Suppose a complete binary tree with n nodes is represented sequentially (depth = log2n + 1 . Then for any node with index i, 1≤ i < n, we have:(1) parent(i) = i/2 if i ≠ 1. If i = 1 (root), no parent.

(2) lchild(i) = 2i if 2i ≤ n. If 2i > n, i has no left child.

(3) rchild(i) = 2i + 1 if 2i + 1 ≤ n. If 2i + 1 > n, no right child.

� Skewed Tree: waste space

Chap 5: Trees (Page 14)

E

.

.

.

--

D

--

--

--

C

--

B

A

[16]

.

.

.

[9]

[8]

[7]

[6]

[5]

[4]

[3]

[2]

[1]

I[9]

H[8]

G[7]

F[6]

E[5]

D[4]

C[3]

B[2]

A[1]

Figure 5.11: Array representation of binary trees of Figure 5.9

Page 8: Chapter 5. TREES - YUynucc.yu.ac.kr/~hrcho/Courses/DS/Chap5.pdfChap 5: Trees(Page 1) Chapter 5. TREES 1. INTRODUCTION 2. BINARY TREES 3. BINARY TREE TRAVERSALS 4. ADDITIONAL BINARY

� Linked Representation

typedef struct node *tree_pointer;

typedef struct node {int data;tree_pointer left_child, right_child;

};

right_childdataleft_child

data

left_child right_child

Chap 5: Trees (Page 15)

Figure 5.13: Linked representation for the binary trees of Figure 5.9

Chap 5: Trees (Page 16)

NULLA

NULLB

NULLC

NULLD

NULLE

root

Aroot

B C

D NULLENULL NULLFNULL NULLGNULL

NULLHNULL NULLINULL

Page 9: Chapter 5. TREES - YUynucc.yu.ac.kr/~hrcho/Courses/DS/Chap5.pdfChap 5: Trees(Page 1) Chapter 5. TREES 1. INTRODUCTION 2. BINARY TREES 3. BINARY TREE TRAVERSALS 4. ADDITIONAL BINARY

Chap 5: Trees (Page 17)

3. BINARY TREE TRAVERSAL

� Problem Definition✔ Visiting Exach Node Exactly Once

✔ Produce Linear Order in a Tree

+

E*

D*

C/

A B

� Inorder Traversal

void inorder(tree_pointer ptr){

if (ptr) {inorder(ptr->left_child);printf("%d", ptr->data);inorder(ptr->right_child);

}}

⇒ ��¦¦¥¥¡¦¡¦¥¥kk r `r ` ss [ t[ t [[ uu \\ vv

Chap 5: Trees (Page 18)

+

E*

D*

C/

A B

Page 10: Chapter 5. TREES - YUynucc.yu.ac.kr/~hrcho/Courses/DS/Chap5.pdfChap 5: Trees(Page 1) Chapter 5. TREES 1. INTRODUCTION 2. BINARY TREES 3. BINARY TREE TRAVERSALS 4. ADDITIONAL BINARY

� Preorder Traversal

void preorder(tree_pointer ptr){

if (ptr) {printf("%d", ptr->data);preorder(ptr->left_child);

preorder(ptr->right_child);}

}

⇒ �¦�¦¥¡¦¥¡¦¥¥kk \\ [[ [ `[ ` rr s ts t uu vv

Chap 5: Trees (Page 19)

+

E*

D*

C/

A B

� Postorder Traversal

void postorder(tree_pointer ptr)

{

if (ptr) {

postorder(ptr->left_child);

postorder(ptr->right_child);

printf("%d", ptr->data);

}

}

⇒ �¦�¦¥¡¦¥¡¦¥¥kk rr s `s ` tt [[ uu [[ vv \\

Chap 5: Trees (Page 20)

� Iterative Inorder Traversal: Complexity = O(n)� Level Order Traversal: Breadth First Search

✔ + * E * D / C A B

+

E*

D*

C/

A B

Page 11: Chapter 5. TREES - YUynucc.yu.ac.kr/~hrcho/Courses/DS/Chap5.pdfChap 5: Trees(Page 1) Chapter 5. TREES 1. INTRODUCTION 2. BINARY TREES 3. BINARY TREE TRAVERSALS 4. ADDITIONAL BINARY

void iter_inorder(tree_pointer node){

int top = -1; /* initialize stack */tree_pointer stack[MAX_STACK_SIZE];for (; ;) {

for (; node; node = node->left_child)add(&top, node);

node = delete(&top);if (!node)break; /* empty stack */printf(“%d”, node->data);node = node->right_child;

}}

Chap 5: Trees (Page 21)

Program 5.4: Iterative Inorder Traversal

void level_order(tree_pointer ptr)/* level order tree traversal */{

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

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;

}}

Chap 5: Trees (Page 22)

Program 5.5: Level order traversal of a binary tree

Page 12: Chapter 5. TREES - YUynucc.yu.ac.kr/~hrcho/Courses/DS/Chap5.pdfChap 5: Trees(Page 1) Chapter 5. TREES 1. INTRODUCTION 2. BINARY TREES 3. BINARY TREE TRAVERSALS 4. ADDITIONAL BINARY

Chap 5: Trees (Page 23)

4. ADDITIONAL BINARY TREE OPERATION

� Copying Binary Trees✔ See Program 5.6: Modified Version of postorder✔ Design swap_tree: See Exercise 2 (Page 210)

� Testing for Equality of Binary Trees✔ See Program 5.7: Modified Version of preorder

� The Satisfiability Problem✔ Find Assignment of Values that Satisfy Expression✔ (x1 & !x2) | (!x1 & x3) | !x3

✔ Generate 2n Combinations & Evaluate Each of them✔ See Program 5.8 and Program 5.9

tree_pointer copy(tree_pointer original)/* this function returns a tree_pointer to an exact copy of the original

tree */{

tree_pointer temp;if (original) {

temp = (tree_pointer) malloc(sizeof(node));if (IS_NULL(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;

}

Chap 5: Trees (Page 24)

Program 5.6: Copying a binary tree

Page 13: Chapter 5. TREES - YUynucc.yu.ac.kr/~hrcho/Courses/DS/Chap5.pdfChap 5: Trees(Page 1) Chapter 5. TREES 1. INTRODUCTION 2. BINARY TREES 3. BINARY TREE TRAVERSALS 4. ADDITIONAL BINARY

int equal(tree_pointer first, tree_pointer second)

{/* function return 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))}

Chap 5: Trees (Page 25)

Program 5.7: Testing for equality of binary trees

Chap 5: Trees (Page 26)

∨ ¬

¬ X3

X1 ¬

X2 X1

X3

Page 14: Chapter 5. TREES - YUynucc.yu.ac.kr/~hrcho/Courses/DS/Chap5.pdfChap 5: Trees(Page 1) Chapter 5. TREES 1. INTRODUCTION 2. BINARY TREES 3. BINARY TREE TRAVERSALS 4. ADDITIONAL BINARY

� Node structure in Ctypedef enum {not, and, or, true, false} logical;typedef struct node *tree_pointer;typedef struct node {

tree_pointer left_child, right_child;logical data;short int value;

};

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;} }

Program 5.8: First version of satisfiability algorithm

Chap 5: Trees (Page 27)

Chap 5: Trees (Page 28)

void post_order_eval(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;

} } }

Program 5.9: post_order_eval function

Page 15: Chapter 5. TREES - YUynucc.yu.ac.kr/~hrcho/Courses/DS/Chap5.pdfChap 5: Trees(Page 1) Chapter 5. TREES 1. INTRODUCTION 2. BINARY TREES 3. BINARY TREE TRAVERSALS 4. ADDITIONAL BINARY

Chap 5: Trees (Page 29)

5. THREADED BINARY TREE

� Basic Idea ✔ n + 1 null links out of 2n total links

✔ Replace null links by pointers to other nodes

⇒ Threads

� Usage of Threads✔ ptr->left_child = ∅ : inorder predecessor of ptr

✔ ptr->right_child = ∅ : inorder successor of ptr

� Node structuretypedef struct thread_tree *threaded_pointer;

Typedef struct thread_tree {short int left_thread;threaded_pointer left_child;

char data;threaded_pointer right_child;short int right_thread;

};

Figure 5.21: Threaded tree corresponding to Figure 5.9(b)

Chap 5: Trees (Page 30)

A

B

D

H I

E

C

F G

root

Page 16: Chapter 5. TREES - YUynucc.yu.ac.kr/~hrcho/Courses/DS/Chap5.pdfChap 5: Trees(Page 1) Chapter 5. TREES 1. INTRODUCTION 2. BINARY TREES 3. BINARY TREE TRAVERSALS 4. ADDITIONAL BINARY

� Head Node of Threaded Binary Tree✔ Inorder predecessor of leftmost node

✔ Inorder successor of rightmost node

An Empty Threaded Binary Tree

FALSE•____•TRUE

right_threadright_childdataleft_childleft_thread

Chap 5: Trees (Page 31)

Figure 5.23: Memory representation of a threaded tree

Chap 5: Trees (Page 32)

f•A•f

f•B•f f•C•f

f•D•f t•E•t t•F•t t•G•t

t•H•t t•I•t

f•-•froot

f = FALSEt = TRUE

Page 17: Chapter 5. TREES - YUynucc.yu.ac.kr/~hrcho/Courses/DS/Chap5.pdfChap 5: Trees(Page 1) Chapter 5. TREES 1. INTRODUCTION 2. BINARY TREES 3. BINARY TREE TRAVERSALS 4. ADDITIONAL BINARY

� Inorder Traversal of a Threaded Binary Tree✔ If ptr->right_thread == TRUE

⇒ Inorder Successor of ptr = ptr->right_child

✔ Otherwise⇒ Following left_child links from right_child of ptr until we reach a

node with left_thread = TRUE

✔ Program 5.10 & Program 5.11: Complexity = O(n)

✔ Exercise 4/5: preorder/postorder traversal with threads

� Inserting A Node Into A Threaded Binary Tree✔ Insert new node as right child of parent

✔ Two cases: parent->right_thread is TRUE or FALSE

✔ See Figure 5.24 & Program 5.12

✔ Exercise 3: insert new node as left child of parent

Chap 5: Trees (Page 33)

threaded_pointer insucc(threaded_pointer tree){

/* find the inorder sucessor of tree in a threaded binary tree */threaded_pointer temp;temp = tree->right_child;if (!tree->right_thread)

while (!temp->left_thread) temp = temp->left_child;return temp;

Chap 5: Trees (Page 34)

void tinorder (threaded_pointer tree){/* traverse the threaded binary tree inorder */

threaded_pointer temp = tree;for ( ; ; ) {

temp = insucc(temp);if (temp = tree) break;printf(“%3c”, temp->data);

}

Program 5.10: Finding the inorder successor of a node

Program 5.11: Inorder traversal of a threaded binary tree

Page 18: Chapter 5. TREES - YUynucc.yu.ac.kr/~hrcho/Courses/DS/Chap5.pdfChap 5: Trees(Page 1) Chapter 5. TREES 1. INTRODUCTION 2. BINARY TREES 3. BINARY TREE TRAVERSALS 4. ADDITIONAL BINARY

Figure 5.24 Insertion of child as a right child of parent in a threaded binary tree

Chap 5: Trees (Page 35)

(a)

A

C

B

root

D

parent

child

before

A

C

B

root

D

parent

child

after

Figure 5.24 Insertion of child as a right child of parent in a threaded binary tree

Chap 5: Trees (Page 36)

(b)

A

C

B

root

D

child

before

E F

parent

X

after

A

C

B

root

D

child

E F

parent

X

Page 19: Chapter 5. TREES - YUynucc.yu.ac.kr/~hrcho/Courses/DS/Chap5.pdfChap 5: Trees(Page 1) Chapter 5. TREES 1. INTRODUCTION 2. BINARY TREES 3. BINARY TREE TRAVERSALS 4. ADDITIONAL BINARY

Chap 5: Trees (Page 37)

void insert_right(threaded_pointer parent, threaded_pointer child){/* insert child as the right child of parent in a threaded binary tree */

threaded_pointer temp;

child->right_child = parent->right_child;child->right_thread = parent->right_threadchild->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;

}}

Program 5.12: Right insertion in a threaded binary tree

Chap 5: Trees (Page 38)

6. HEAPS

� The Heap Abstract Data Type

� Priority Queues� Insertion into a Max Heap

� Deletion from a Max Heap

Page 20: Chapter 5. TREES - YUynucc.yu.ac.kr/~hrcho/Courses/DS/Chap5.pdfChap 5: Trees(Page 1) Chapter 5. TREES 1. INTRODUCTION 2. BINARY TREES 3. BINARY TREE TRAVERSALS 4. ADDITIONAL BINARY

Chap 5: Trees (Page 39)

6.1 The Heap Abstract Data Type

� Definition: max tree & max heap✔ max tree: key value of a node ≥ key values of children✔ max heap: complete binary tree & max tree

� Definition: min tree & min heap✔ min tree: key value of a node ≤ key values of children

✔ min heap: complete binary tree & min tree

Chap 5: Trees (Page 40)

6.2 Priority Queues

� What is a priority queue?✔ Deletes an element with highest (or lowest) priority

� Priority Queue Representations

O(log2n)O(log2n)Max heap

Θ(1)O(n)Sorted linked list

Θ(1)O(n)Sorted array

Θ(n)Θ(1)Unordered linked list

Θ(n)Θ(1)Unordered array

DeletionInsertionRepresentation

Page 21: Chapter 5. TREES - YUynucc.yu.ac.kr/~hrcho/Courses/DS/Chap5.pdfChap 5: Trees(Page 1) Chapter 5. TREES 1. INTRODUCTION 2. BINARY TREES 3. BINARY TREE TRAVERSALS 4. ADDITIONAL BINARY

Chap 5: Trees (Page 41)

14

712

810 6

[1]

[2]

[4] [5]

[3]

[6]

9

36

5

[1]

[2]

[4]

[3]

30

25

[1]

[2]

Figure 5.25: Sample max heaps

2

47

810 6

[1]

[2]

[4] [5]

[3]

[6]

10

8320

50

[1]

[2]

[4]

[3]

11

21

[1]

[2]

Figure 5.26: Sample min heaps

Structure 5.2: Abstract data type MaxHeap

Chap 5: Trees (Page 42)

structure MaxHeap is

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 childrenfunctions:

for all heap ∈ MaxHeap, item ∈ Element, n, max_size ∈ integer

MaxHeap Create(max_size) ::= create an empty heap that can hold amaximum of max_size elements.

Boolean HeapFull(heap, n) ::= if (n == max_size) return TRUE

else return FALSEMaxHeap 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

else return TRUE

Element Delete(heap, n) ::= if (!HeapEmpty(heap, n)) return one instance of the largest element in the heap and remove it from the heap elsereturn error.

Page 22: Chapter 5. TREES - YUynucc.yu.ac.kr/~hrcho/Courses/DS/Chap5.pdfChap 5: Trees(Page 1) Chapter 5. TREES 1. INTRODUCTION 2. BINARY TREES 3. BINARY TREE TRAVERSALS 4. ADDITIONAL BINARY

Chap 5: Trees (Page 43)

6.3 Insertion Into A Max Heap

� Use Array Representation✔ Insert new node to last position

✔ Compare & Replace it until root

� C Declarations

� See Figure 5.28 & Program 5.13: Complexity = O(log2n)

#define MAX_ELEMENTS 200 /*maximum heap size+1 */#define HEAP_FULL(n) (n == MAX_ELEMENTS-1)#define HEAP_EMPTY(n) (!n)typedef struct {

int key;/* other fields */

} element;element heap[MAX_ELEMENTS];int n = 0;

Figure 5.28: Insertion into a max heap

Chap 5: Trees (Page 44)

15

(a) heap before insertion

20

2

14 10

[1]

[2] [3]

[4] [5]

15

(b) Initial location of new node

20

2

14 10

[1]

[2] [3]

[4] [5]

[6]

15

(c) Insert 5 into heap (a)

20

5

14 10

[1]

[2] [3]

[4] [5] 2

[6]

15

(d) Insert 21 into heap (a)

21

20

14 10

[1]

[2] [3]

[4] [5]

[6]

2

Page 23: Chapter 5. TREES - YUynucc.yu.ac.kr/~hrcho/Courses/DS/Chap5.pdfChap 5: Trees(Page 1) Chapter 5. TREES 1. INTRODUCTION 2. BINARY TREES 3. BINARY TREE TRAVERSALS 4. ADDITIONAL BINARY

Chap 5: Trees (Page 45)

Void insert_max_heap(element item, int *n){/* insert item into a max heap of current size *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;

}

Program 5.13: Insertion into a max heap

Chap 5: Trees (Page 46)

6.4 Deletion From A Max Heap

� Basic Idea✔ Delete root node & Move last node to root

✔ Reestablish the heap by moving down & comparing

� See Figure 5.29 & Program 5.14: ✔ Complexity = O(log2n)

Page 24: Chapter 5. TREES - YUynucc.yu.ac.kr/~hrcho/Courses/DS/Chap5.pdfChap 5: Trees(Page 1) Chapter 5. TREES 1. INTRODUCTION 2. BINARY TREES 3. BINARY TREE TRAVERSALS 4. ADDITIONAL BINARY

Figure 5.29: Deletion from a max heap

Chap 5: Trees (Page 47)

[4]

15

(a) Heap structure

2

14 10

[1]

[2] [3]

[5]

20removal

15

(b) 10 inserted at the root

2

14

[1]

[2] [3]

[4]

10

14

(c) Final heap

15

2

14

[1]

[2] [3]

[4] 10

Program 5.14: Deletion from a max heap

Chap 5: Trees (Page 48)

element delete_max_heap (int *n){

int parent, child;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) {

if ((child < *n) && (heap[child].key < heap[child+1].key))child++;

if (temp.key >= heap[child].key) break;heap[parent] = heap[child];parent = child;child *= 2;

}heap[parent] = temp;return item;

}

Page 25: Chapter 5. TREES - YUynucc.yu.ac.kr/~hrcho/Courses/DS/Chap5.pdfChap 5: Trees(Page 1) Chapter 5. TREES 1. INTRODUCTION 2. BINARY TREES 3. BINARY TREE TRAVERSALS 4. ADDITIONAL BINARY

Chap 5: Trees (Page 49)

7. BINARY SEARCH TREES

� Problems of Heap✔ Deletion of arbitrary element: O(n)

✔ Searching for an arbitrary element: O(n)

� Definition: binary search tree✔ Every element has a unique key

✔ Keys in a nonempty left subtree < Key of root✔ Keys in a nonempty right subtree > Key of root

✔ Left & right subtrees are also binary search trees

Figure 5.30: Binary trees

Chap 5: Trees (Page 50)

5

(b)

30

40

3

15

(a)

20

25

12 10 22

(c)

60

70

65 80

Page 26: Chapter 5. TREES - YUynucc.yu.ac.kr/~hrcho/Courses/DS/Chap5.pdfChap 5: Trees(Page 1) Chapter 5. TREES 1. INTRODUCTION 2. BINARY TREES 3. BINARY TREE TRAVERSALS 4. ADDITIONAL BINARY

Chap 5: Trees (Page 51)

7.1 Searching a Binary Search Tree

� Basic Idea✔ If (key == root->key) return(root)

✔ If (key < root->key) search(root->left_child)

Otherwise, search(root->right_child)

✔ Program 5.15 (recursive) & Program 5.16 (iterative)

✔ Complexity: O(height of tree)

Chap 5: Trees (Page 52)

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);

}

Program 5.15: Recursive search of a binary search tree

Page 27: Chapter 5. TREES - YUynucc.yu.ac.kr/~hrcho/Courses/DS/Chap5.pdfChap 5: Trees(Page 1) Chapter 5. TREES 1. INTRODUCTION 2. BINARY TREES 3. BINARY TREE TRAVERSALS 4. ADDITIONAL BINARY

Chap 5: Trees (Page 53)

Program 5.16: Iterative search of a binary search tree

tree_pointer search2 (tree_pointer tree, int key){/* return a pointer to the node that contains key.If there is no such node, return NULL. */

while (tree) {if (key == tree->data) return tree;if (key < tree->data)

tree = tree->left_child;else

tree = tree->right_child;}

return NULL;}

Chap 5: Trees (Page 54)

7.2 Inserting Into a Binary Search Tree

� Basic Idea✔ Search tree to verify key uniqueness

✔ Insert element where the search is terminated

✔ modified_search(root, num)

– If num is present, return(NULL)

– Otherwise, return pointer of last node during search

✔ Program 5.17: Complexity = O(height of tree)

Page 28: Chapter 5. TREES - YUynucc.yu.ac.kr/~hrcho/Courses/DS/Chap5.pdfChap 5: Trees(Page 1) Chapter 5. TREES 1. INTRODUCTION 2. BINARY TREES 3. BINARY TREE TRAVERSALS 4. ADDITIONAL BINARY

Figure 5.31: Inserting into a binary search tree

Chap 5: Trees (Page 55)

5

(a) Insert 80

30

40

2 80

5

(b) Insert 35

30

40

2 8035

Program 5.17: Inserting an element into a binary search tree

Chap 5: Trees (Page 56)

void insert_node (tree_pointer *node, int num)/* If num is in the tree pointed at by node do nothing;Otherwise add a new node with data = num */{

tree_pointer ptr, temp = modified_search (*node, num);if (temp || !(*node)) {

/* num is not in the tree */ptr = (tree_pointer)malloc(sizeof(node));if (IS_FULL (ptr)) {

fprintf(stderr, “The memory is full\n”);exit(1);

}ptr->data = num;ptr->left_child = ptr->right_child = NULL;if (*node) /* insert as child of temp */

if (num < temp->data) temp->left_child = ptr;else temp->right_child = ptr;

else *node = ptr;}

}

Page 29: Chapter 5. TREES - YUynucc.yu.ac.kr/~hrcho/Courses/DS/Chap5.pdfChap 5: Trees(Page 1) Chapter 5. TREES 1. INTRODUCTION 2. BINARY TREES 3. BINARY TREE TRAVERSALS 4. ADDITIONAL BINARY

Chap 5: Trees (Page 57)

7.3 Deletion From a Binary Search Tree

� Basic Idea✔ Deletion of leaf node: parent->left_child = NULL

– (Ex) Delete 35 from Figure 5.31(b)

✔ Deletion of non-leaf node that has only a single child

– Place child in the place of erased node

– (Ex) Delete 40 from Figure 5.31(a)

✔ Deletion of non-leaf node with two children

– Replace node with largest element in left subtree

or with smallest element in right subtree

– See Figure 5.33

Figure 5.33: Deletion of a node with two children

Chap 5: Trees (Page 58)

20

(a) tree before deletion of 60

40

60

10 7030 50

5545

52

(b) tree after deletion of 60

20

40

55

10 7030 50

45 52

Page 30: Chapter 5. TREES - YUynucc.yu.ac.kr/~hrcho/Courses/DS/Chap5.pdfChap 5: Trees(Page 1) Chapter 5. TREES 1. INTRODUCTION 2. BINARY TREES 3. BINARY TREE TRAVERSALS 4. ADDITIONAL BINARY

Chap 5: Trees (Page 59)

7.4 Height of a Binary Search Tree

� Worst case: O(n), Average case: O(log2n)� Balanced Binary Search Tree: AVL Tree, B Tree

Chap 5: Trees (Page 60)

9. FORESTS

� Definition: forestset of n ≥ 0 disjoint trees

� Definition: binary tree representation of forest T1, .., Tn

(1) is empty if n = 0

(2) root = root(T1), left subtree = subtree of T1

right subtree = B(T2, ..., Tn)

Page 31: Chapter 5. TREES - YUynucc.yu.ac.kr/~hrcho/Courses/DS/Chap5.pdfChap 5: Trees(Page 1) Chapter 5. TREES 1. INTRODUCTION 2. BINARY TREES 3. BINARY TREE TRAVERSALS 4. ADDITIONAL BINARY

Chap 5: Trees (Page 61)

A

C DB

E

F

G

IH

A

C

D

B E

F G

I

H

A

C

D

B

E

F

G

I

H

� Preorder Traversal of Forest F(1) If F is empty, then return

(2) Visit root of first tree of F

(3) Traverse subtrees of first tree in preorder

(4) Traverse remaining trees of F in preorder

� Inorder Traversal of Forest F(1) If F is empty, then return

(2) Traverse subtrees of first tree in inorder

(3) Visit root of first tree of F

(4) Traverse remaining trees of F in inorder

Chap 5: Trees (Page 62)

Page 32: Chapter 5. TREES - YUynucc.yu.ac.kr/~hrcho/Courses/DS/Chap5.pdfChap 5: Trees(Page 1) Chapter 5. TREES 1. INTRODUCTION 2. BINARY TREES 3. BINARY TREE TRAVERSALS 4. ADDITIONAL BINARY

Chap 5: Trees (Page 63)

10. SET REPRESENTATION

� Assumptions✔ The elements of the sets are the number 0, 1, 2, ..., n-1.✔ The sets being represented are pairwise disjoint, that is, if Si and Sj

are two sets and i ≠ j, then there is no element that is in both Si and Sj .

� Minimal operations on these sets:(1) Disjoint set union

Si and Sj: two disjoint setsSi ∪ Sj = {x | such that x ∈ Si or x ∈ Sj}

(2) Find(i)Find the set containing the element, i.

� Representation of sets✔ S1 = { 0, 6, 7, 8 }, S2 = { 1, 4, 9 }, S3 = { 2, 3, 5 }

0

6 7 8

2

3

S1 S2

5

S3

4

1 9

Chap 5: Trees (Page 64)

Page 33: Chapter 5. TREES - YUynucc.yu.ac.kr/~hrcho/Courses/DS/Chap5.pdfChap 5: Trees(Page 1) Chapter 5. TREES 1. INTRODUCTION 2. BINARY TREES 3. BINARY TREE TRAVERSALS 4. ADDITIONAL BINARY

4

1 9

0

6 7 8 0

6 7 8

4

1 9

� union (S1, S2)

S1 ∪ S2S2 ∪ S1

Chap 5: Trees (Page 65)

S1

S2

S3

setname pointer 0

6 7 84

1 9

2

3 5

� Data Representation of S1, S2 and S3

Chap 5: Trees (Page 66)

Page 34: Chapter 5. TREES - YUynucc.yu.ac.kr/~hrcho/Courses/DS/Chap5.pdfChap 5: Trees(Page 1) Chapter 5. TREES 1. INTRODUCTION 2. BINARY TREES 3. BINARY TREE TRAVERSALS 4. ADDITIONAL BINARY

�Array representation of S1, S2, and S3

int find1(int i)

{for ( ; parent[i] >= 0; i = parent[i] ) ;return i;

}void union1(int i, int j){

parent[i] = j;}

Chap 5: Trees (Page 67)

40002-12-14-1parent

[9][8][7][6][5][4][3][2][1][0]i

� Degenerate tree✔ union(0, 1), union(1, 2), ..., union(n - 2, n - 1)

n-1

n-2

.

.

0

Degenerate tree

Chap 5: Trees (Page 68)

Page 35: Chapter 5. TREES - YUynucc.yu.ac.kr/~hrcho/Courses/DS/Chap5.pdfChap 5: Trees(Page 1) Chapter 5. TREES 1. INTRODUCTION 2. BINARY TREES 3. BINARY TREE TRAVERSALS 4. ADDITIONAL BINARY

� Definition: Weighting rule for union(i, j)✔ 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.

0 1 n--1... 0 ... 0 3 ...

.. 0

3 ...

initialunion(0,1)0 = find(0) union(0,2)

0 = find(0)

union(0, n-1)

0

3

4 ...

union(0,3), ...,0 = find(0)

Chap 5: Trees (Page 69)

2

1

n--1

21

n--1

n--1

21 n--121

Chap 5: Trees (Page 70)

void union2 (int n, int j){/* union the sets with roots i and j, i != j, using the weighting rule. parent[i] = -count[i] and parent[j] = -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;

}}

Program 5.19 : Union function

Page 36: Chapter 5. TREES - YUynucc.yu.ac.kr/~hrcho/Courses/DS/Chap5.pdfChap 5: Trees(Page 1) Chapter 5. TREES 1. INTRODUCTION 2. BINARY TREES 3. BINARY TREE TRAVERSALS 4. ADDITIONAL BINARY

Chap 5: Trees (Page 71)

Figure 5.45 : Trees achieving worst case bound

0

[-1]

1

[-1]

2

[-1]

3

[-1]

4

[-1]

5

[-1]

6

[-1]

7

[-1] Level1

CommandInitial

0

1

[-2]

2

3

[-2]

4

5

[-2]

6

7

[-2]

1

2

union(0,1)union(2,3)union(4,5)union(6,7)

1

0

2

3

[-4]

5

4

6

7

[-4]1

2

3

union(0,2)union(4,6)

1

0

2

3 5

4

6

7

[-8] 1

2

3

4

union(0,4)

� Lemma 5.4 [Complexity of union2]✔ T: tree with n nodes created as a result of union2

⇒ No node in T has level greater than log2n + 1� Definition [Collapsing Rule]

✔ If j is a node on the path from i to its root, then make j a child of the root.

Chap 5: Trees (Page 72)

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 != root; trail = lead) {

lead = parent[trail];parent[trail] = root;

}return root;

}

Program 5.20 : Find function

Page 37: Chapter 5. TREES - YUynucc.yu.ac.kr/~hrcho/Courses/DS/Chap5.pdfChap 5: Trees(Page 1) Chapter 5. TREES 1. INTRODUCTION 2. BINARY TREES 3. BINARY TREE TRAVERSALS 4. ADDITIONAL BINARY

(Ex) 8 find(7)– without collapsing : 24 moves

– With collapsing : 12 moves

� Equivalent Classes– Two finds & at most one union

– Effcient Space Usae : O(m + n) vs. O(n)

– See Figure 5.46

Chap 5: Trees (Page 73)

Chap 5: Trees (Page 74)

Figure 5.46 : Trees for equivalence example

[-4]

0

[-1]

1

[-1]

2

[-1]

3

[-1]

4

[-1]

5

[-1]

6

[-1] INPUTInitial7

[-1]

8

[-1]

9

[-1]

10

[-1]11

[-1]

0 ≡ 43 ≡ 16 ≡ 108 ≡ 9

0

4

[-2]

3

1

[-2]

2

[-1]

6

10

[-2]

8

9

[-2]

11

[-1][-1]

75

[-1]

4

0

7

[-3]

10

6

8

9

1

3

5

[-3]

2

11

[-2] 7 ≡ 46 ≡ 83 ≡ 52 ≡ 11

4

0

7

[-5]

2

11

10

6

8

9

[-4]

1

3

5

[-3] 11 ≡ 0

Page 38: Chapter 5. TREES - YUynucc.yu.ac.kr/~hrcho/Courses/DS/Chap5.pdfChap 5: Trees(Page 1) Chapter 5. TREES 1. INTRODUCTION 2. BINARY TREES 3. BINARY TREE TRAVERSALS 4. ADDITIONAL BINARY

Chap 5: Trees (Page 75)

11. COUNTING BINARY TREES

� Constructing Binary Tree✔ Preorder : A B C D E F G H I (←Postorder?)✔ Inorder : B C A E D G H F I

B,C

A

D, E, F, G, H, I

(a)

B

A

D, E, F, G, H, I

C (b)

B

A

D

FC E

IG

H(c)

Chap 5: Trees (Page 76)

� The Followings are Equal✔ # of distinct binary trees having n nodes

✔ # of distinct stack permutations for n data

✔ # of distinct ways of multiplying n+1 matrices