120
•1

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

Embed Size (px)

Citation preview

Page 1: 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

•1

Page 2: 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

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

Page 3: 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

•3

K

E F G H JI

B DC

A

L M

1

2

3

4

Level

Page 4: 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

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

Page 5: 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

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

Page 6: 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

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

•6

data link 1 link 2 link n· · ·

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

Representation of trees left-child right-sibling representation

nodes of a fixed sizeeasier to work two link / pointer fields per node

left-child right-sibling node structure

•7

data

left child right sibling

Page 8: 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

left-child right-sibling representation of a tree•8

K

E F G H JI

B DC

A

L M

Page 9: 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

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 childdegree 2binary tree

•9

Page 10: 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

left-child right-child tree representation of a tree

•10

K

E

F G

H

J

I

B

D

C

A

L

M

Page 11: 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

tree representations

•11

A

B

A

B

A

B C

A

B

C

A

B C

A

B

tree

tree

left child-right sibling tree

left child-right sibling tree

binary tree

binary tree

Page 12: 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

•12

Page 13: 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

Def) Binary tree is a finite set of nodes such that

1) empty or2) consists of root node and two disjoint binary

trees, called, left subtree and right subtree

two different binary trees

•13

A

B

A

B

Page 14: 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

Properties of binary trees Difference between a binary tree and a tree

may have empty node the order of subtree are importanta binary tree is not a subset of a treemaximum 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

Page 15: 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

Special types of binary trees Skewed binary tree

Full binary tree (of depth k)a binary tree of depth k(0) having 2k - 1 nodes

Complete binary treea binary tree with n nodes that correspond to the

nodes numbered from 1 to n in the full binary tree of depth k

•15

Page 16: 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

Full binary tree of depth 4 with sequential node numbers

•16

9

4

2

5 6

1

7

3

8 1110 1312 1514

Page 17: 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

skewed and complete binary trees

•17

I

D

B

E F

A

G

C

H

C

E

B

D

A

skewed binary tree complete binary tree

Page 18: 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

Binary tree representation Array representation

Sequential representationsDetermine 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 2in

3) right_child(i) is at 2·i + 1 if 2·i + 1 n

•18

Page 19: 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

Array representation of binary trees•19

[9]

[8]

[7]

[6]

[5]

[4]

[3]

[2]

[1]

I

H

G

F

E

D

C

B

A

·

·

-

D

-

-

-

C

-

B

A

E

·

[9]

[8]

[7]

[6]

[5]

[4]

[3]

[2]

[1]

[16]

·

·

·

skew binary tree complete binary tree

Page 20: 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

Problems of array representation

inefficient storage utilizationS(n) = 2k-1, where k: depth of binary tree

ideal for complete binary trees hard to insert/delete

•20

Page 21: 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

Linked representation each node has three fields

left_child, data, and right_childtypedef struct node *tree_ptr;typedef struct node {

int data;tree_ptr left_child, right_child;

};

Node representation for binary trees

•21

left_child data right_child

left_child right_child

data

Page 22: 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

Linked representation for the binary trees •22

A NULL

B

C

D

E

NULL

NULL

NULL

NULLNULL

root

H NULLNULL I NULLNULL

E NULLNULL F NULLNULL G NULLNULLD

B C

Aroot

skewed binary tree complete binary tree

Page 23: 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

Leaf node’s link fields contain null pointer

Add a fourth field, parent, to know the parent of random nodes

•23

data NULLNULL

leaf node

data right_childleft_child

parent

left_child right_child

data

parent

Page 24: 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

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 linksnumber of non-null links: n-1 (n: # of nodes)number of null links: n·k - (n-1)

•24

Page 25: 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

Convert a tree into a binary tree1) (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

Page 26: 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

•26

CB

A

D

FE G

CB

A

D

FE G

C

B

A

DF

E

G

tree

left child-right sibling tree

binary tree

Page 27: 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

•27

Page 28: 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

Visit each node in the tree exactly onceproduce a linear order for the information in a treewhat 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

Page 29: 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

Binary tree with arithmetic expression

•29

*

+

E

* D

/ C

A B

6 7 9 10

12 13

15 16

18 19

5

4

3

2

1

17

14

11

8

A / B * C * D + E (infix form)

Page 30: 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

Inorder traversalvoid 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+Ecorresponds to the infix form

•30

Page 31: 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

trace of inorder

•31

call ofinorder

value inroot

action call ofinorder

value inroot

action

123456574898

103

+**/

ANULL

ANULL

/B

NULLB

NULL*

printf

printf

printf

printf

11121113

214151416

117181719

CNULL

CNULL

*D

NULLD

NULL+E

NULLE

NULL

printf

printf

printf

printf

printf

Page 32: 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

Preorder traversalvoid preorder(tree_ptr ptr) {

if(ptr) {printf(“%d”, ptr->data);preorder(ptr->left_child);preorder(ptr->right_child);

}}

output in the order: +**/ABCDEcorrespond to the prefix form

•32

Page 33: 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

Postorder traversalvoid 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

Page 34: 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

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

Page 35: 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

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

Page 36: 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

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

Page 37: 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

Level order traversal traversal by using queue(FIFO)

Output in the order: 123456789•••15 for previous example: +*E*D/CAB

•37

9

4

2

5 6

1

7

3

8 1110 1312 1514

Page 38: 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

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

Page 39: 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

Copying binary treesmodified version of postordertree_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

Page 40: 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

Testing for equality of binary treesmodified 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

Page 41: 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

•41

Page 42: 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

There are more null links than actual pointers in representation of any binary treen+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

Page 43: 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

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

Page 44: 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

Threaded binary tree

•44

I

D

B

E F

A

G

C

H

Page 45: 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

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

Page 46: 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

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;

};

Threaded node structure

•46

left_thread right_threadright_childdataleft_child

Page 47: 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

Two threads have been left danglingthe left child of Hthe right child of G

How to use two dangling links?add a head(=dummy) node

an empty threaded tree

•47

left_thread right_threadright_childdataleft_child

TRUE FALSE

Page 48: 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

Memory representation of a threaded tree•48

A ff

B ff C ff

E ttD ff F tt G tt

H tt I tt

-- ffroot

f: FALSE

t: TRUE

Page 49: 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

Inorder traversal of a threaded binary tree Find the inorder successor of ptr

if ptr->right_thread=TRUE, ptr->right_childotherwise 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

Page 50: 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

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

Page 51: 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

Inorder traversal repeated calls to insucc() time: O(n), where n: number of nodes in a

threaded binary treevoid 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

Page 52: 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

Inserting a node into a threaded binary tree Insert child as the right child of parent

1) change parent->right_thread to FALSE2) set child->left_thread and child->right_thread to

TRUE3) set child->left_child to point to parent4) set child->right_child to point to parent->right_child5) change parent->right_child to point to child6) if parent has nonempty right child, child becomes the

inorder predecessor of the node that was previously parent’s inorder successor

•52

Page 53: 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

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

Page 54: 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

•54

C

A

B

D

root

parent

childC

A

B

D

root

parent

child

before after

Page 55: 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

•55

C

A

B

D

root

parent

child

E F

X

C

A

B

D

root

parent

child

E F

X

before after

Page 56: 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

•56

Page 57: 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

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

Page 58: 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

Representation of max(min) heaps

Array representationbecause heap is a complete binary treesimple addressing scheme for parent, left(right)

child

•58

Page 59: 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

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

Page 60: 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

sample max heaps

•60

[1]14

12

10

7

8 6

[2] [3]

[4] [5] [6]

9

6

5

3

[1]

[2] [3]

[4]

30

25

[1]

[2]

Page 61: 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

sample min heaps

•61

11

21

[1]

[2]

2

7

10

4

8 6

[2] [3]

[4] [5] [6]

[1]

10

20

50

83

[1]

[2] [3]

[4]

Page 62: 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

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

Page 63: 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

We an use max(min) heap to implement the priority queues

possible priority queue representations

•63

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)

Page 64: 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

Insertion into a max heap need to go from a node to its parent

linked representationadd a parent field to each node

array representationa heap is a complete binary treesimple addressing scheme

•64

Page 65: 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

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

Page 66: 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

•66

20

15

14

2

10

[2] [3]

[4] [5]

[1]20

15

14

2

10

[2] [3]

[4] [5] [6]

[1]

20

15

14

5

10 2

[2] [3]

[4] [5] [6]

[1]21

15

14

20

10 6

[2] [3]

[4] [5] [6]

[1]

(a) heap before insertion (b) initial location of new node

(d) inset 21 into heap (a)(c) insert 5 into heap (a)

Page 67: 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

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

Page 68: 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

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(log2n)

•68

Page 69: 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

•69

20

15

14

2

10

[2] [3]

[4] [5]

[1]

10

15

14

2

[1]

[2] [3]

[4]

15

14 2

[1]

[2] [3]

[4]

10

15

14

2

[1]

[2] [3]

[4] [5]

20

removed

(a) heap structure

(b) 10 inserted at the root (c) final heap

Page 70: 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

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

Page 71: 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

•71

Page 72: 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

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

Page 73: 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

•73

20

15

12

25

10

30

5

2

40

60

65

70

80

22 (a) not a BST

(b) BST (c) BST

Page 74: 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

Searching, insertion, deletion is bounded by O(h) where h is the height of the BST

Can perform these operations bothby key value

eg) delete the element whith key xby rank

eg) delete the fifth smallest element inorder traversal of BST

generate a sorted list

•74

Page 75: 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

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

Page 76: 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

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

Page 77: 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

Time complexity for searchingaverage case: O(h), where h is the height of BSTworst case: O(n) for skewed binary tree

•77

Page 78: 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

Inserting into a BST Modified_search is slightly modified version of

function iter_searchreturn NULL, if the tree is empty or num is presentotherwise, 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

Page 79: 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

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

Page 80: 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

Inserting into a BST

•80

30

5

2

40

80

30

5

2

40

8035

(a) insert 80 (b) insert 35

30

5

2

40

Page 81: 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

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 deletingO(h) where h is the height of the tree

•81

Page 82: 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

Deleting a leaf or a node with 1 child

•82

30

5

2

40

80

30

5

2

80

30

5

2

40

8035

(a) delete 35 (leaf) (b) delete 40 (node with single child)

Page 83: 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

Deletion of a node with two children

•83

40

20

10

60

30 50 70

45 55

52

40

20

10

55

30 50 70

45 52

(a) tree before deletion of 60 (b) tree after deletion of 60

Page 84: 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

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

Page 85: 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

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

Page 86: 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

•86

Page 87: 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

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

Page 88: 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

selection tree for k = 8 showing the first three keys in each of the eight runs

•88

1516

run 1

2038

run 2

2030

run 3

1525

run 4

1550

run 5

1116

run 6

100110

run 7

1820

run 8

9

9

6

6 8

6

17

8

10 620 98 1790

1

2 3

4 5 6 7

8 9 10 11 12 13 14 15

Page 89: 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

selection tree after one record has been output and the tree restructured

•89

1516

run 1

2038

run 2

2030

run 3

2525

run 4

1550

run 5

1116

run 6

100110

run 7

1820

run 8

9

9

9

15 8

8

17

8

10 1520 98 1790

1

2 3

4 5 6 7

8 9 10 11 12 13 14 15

: node that is changed

Page 90: 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

Time to set up the selection tree the first time is O(k)

Time to restructure the tree is O(log2k), where

k is the number of runs Time to merge all n records is O(n·log

2k)

total time: O(n·log2k)

•90

Page 91: 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

tree of losers: a tournament tree in which each non-leaf node retains a pointer to the loser slightly faster merging is possible

•91

9

10

9

20 9

8

90

17

10 620 98 1790

1

2 3

4 5 6 7

8 9 10 11 12 13 14 15

60

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

overall

winner

Page 92: 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

•92

Page 93: 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

Def) A forest is a set of n 0 disjoint trees

Removing the root of any tree produce a forest

Forest with three trees

•93

CB

A

D F

E G

H I

Page 94: 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

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

•94

CB

A

D F

E G

H I

Page 95: 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

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

Page 96: 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

Binary tree representation of forest

•96

E

C

B

A

D

F G

H

I

Page 97: 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

Forest traversals preorder traversal

1) if F is empty, then return2) visit the root of the first tree of F3) traverse the subtrees of the first tree in tree

preorder4) traverse the remaining trees of F in preorder

equivalent to the preorder traversal of the corresponding binary tree

•97

Page 98: 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

Forest traversals inorder traversal

1) If F is empty, then return2) traverse the subtrees of the first tree in tree

inorder3) visit the root of the first tree of F4) traverse the remaining trees of F in inorder

equivalent to the inorder traversal of the corresponding binary tree

•98

Page 99: 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

Forest traversals postorder traversal

1) if F is empty, then return2) traverse the subtrees of the first tree in tree

postorder3) traverse the remaining trees of F in postorder4) visit the root of the first tree of F

not equivalent to the inorder traversal of the corresponding binary tree

•99

Page 100: 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

set 표현에 tree 를 사용한다 .

편의상의 가정들

set 의 element 들은 0, 1, 2, … , n-1 임

( 실제로 이 숫자들은 symbol table 의 index 일 수 있음 )

set 들은 pairwise disjoint 하다 .

즉 , 서로 다른 두 set 사이에는 공통 element 가 없다 .

Page 101: 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

set 에서는 node 들간의 link 가 children 으로부터 parent 로 연결되도록 사용함

set 의 기본 연산

disjoint set union

Si, Sj 의 disjoint set 에 대하여 Si S∪ j = {Si 이나 Sj 에 속한 모든 element 들 }

find(i) : element i 를 가진 set 을 찾는다 .

위의 그림에서 3 은 set S3 에 속한다 . 8 은 set S1 에 속한다 .

0

6 87

4

1 9

2

3 5

s1 s2 s3

Page 102: 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

Union and Find Operations Union

set union 을 구현 시 단순히 한 tree 를 다른 tree 의 subtree 로 만든다 .

Si S∪ j 는 다음의 그림과 같이 두 가지 방식으로 실행될 수 있다 .0

6 87 4

1 9

4

0 91

6 87

S1∪ S2 S2∪ S1or

Page 103: 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

set union 을 구현 시 set 의 root 를 찾기 쉽도록 set 을 나타내는 tree 의 root 에 대한 pointer 를 유지하고 element 가 속한 set 의 name 을 찾을 수 있도록 각 root 가 set name 에 대한 pointer 를 유지한다 .

S1

S2

S3

0

6 87

4

1 9

2

3 5

set pointername

Page 104: 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

표현의 용이를 위해서 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

[1]

4

[2]

-1

[3]

2

[4]

-1

[5]

2

[6]

0

[7]

0

[8]

0

[9]

4

root node 의 parent field 값은 -1 을 갖는다 .

Page 105: 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

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

Page 106: 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

Analysis

구현은 용이하나 성능이 떨어진다 .

Example {0}{1}{2}{3}, … ,{p} 로 이루어진 set 에 대하여 다음의 연산을

수행union(0, 1), find(0)

union(1, 2), find(0)

•••

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

이러한 union 연산은 옆의 그림과같은 tree 를 생성하게 되고 find

연산의 성능이 떨어진다 .

p

P-1

1

0

...

degenerate tree

Page 107: 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

union 연산은 매회 constant time 에 이루어지므로 총 소요 시간은 O(n) 임 .

find 연산은 0 에서부터 root 까지 거슬러 올라가야 하므로 i

번째 연산에서 단위 연산의 소요 시간은 O(i) 임 .

따라서 n-1 개의 find 연산에 대한 소요 시간은 i = O(n2)

임 .

Definition

tree i 의 node 개수가 tree j 의 node 개수보다 적으면 i 의 parent 를

j 로 만들고 그렇지 않은 경우 j 의 parent 를 i 로 만든다 .

n

i=2

Page 108: 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

Example 앞의 Example 에 대하여 다음과 같이 실행됨

구현의 용이를 위해 모든 tree 의 root 에 대해 count field 를 유지한다 .

즉 , i 가 root node 이면 count[i] 는 그 tree 에 존재하는 node 의 개수이다 .

여기서는 , root 의 parent 를 count[i] 대신 사용한다 .

0 1 n• • •

0 2 n• • •

0 3 n• • •

1 21union(0,1)0 = find(0)

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

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

intial

0 4 n• • •

321

1

321 1

• • •

• • •

union(0,n)

Page 109: 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

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

}

Page 110: 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

Analysis

union2, find1 의 사용 시 time complexity

1 find time (log2n)

n-1 union, m find time (n+m log2n)

Definition

[Collapse Rule]

j 가 i 에서 root 까지의 path 상에 있는 node 라 하면 j 를

root 의 child 로 만든다 .

Page 111: 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

Program 18 은 find 연산에 Collapse Rule 을 포함시킨 것이다 .

이 function 은 각각의 find 의 수행에는 두 배 정도의 시간을

소요하지만 find 연산들의 sequence 의 수행시 worst case

time 을

줄여 준다 .

Page 112: 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

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 ;

}

Page 113: 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

다음 문제들의 정답이 동등

n 개의 노드를 가진 서로 다른 이진 트리의 수

스택을 이용하여 얻을 수 있는 1 에서 n 까지의 서로 다른 순열의 수

n+1 개의 행렬을 곱하는 서로 다른 방법의 수

Page 114: 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

Distinct Binary Trees node 수에 따른 distinct binary tree 의 개수는 ?

n : node 의 수n = 0 또는 n = 1 binary tree 는 한 개만 존재

n = 2 두개의 binary tree

n = 3 5 개의 binary tree

n = k ?

Page 115: 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

stack permutations binary tree 는 unique 한 preorder / inorder sequence pair 를

가지고 있다 .

Example

preorder sequence A B C D E F G H I

inorder sequence B C A E D G H F I

Page 116: 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

A

I

C

B

A

H

G

A

B

FEC

D

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

(a) (b)

(c)

•Constructing a binary tree from its inorder and preorder sequences

Page 117: 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

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

Page 118: 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

다섯 개의 ( 1, 2, 3 ) ( 1, 3, 2 ) ( 2, 1, 3 ) ( 2, 3, 1 ) ( 3, 2, 1 ) 순열들

은 세 개의 노드를 가진 서로 다른 다섯 개의 이진 트리와

일치함

1

2

3

1 1 1 1

2 2 2 2

3

3

3 3

Page 119: 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

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

Page 120: 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

•120

1 1n ,bbb 0

1-n

1i1-i-nin

b그리고

•bn = 루트 , 노드 수가 bi, bn-i-1 인 서브트리로 된 이진트리들