Upload
dulcie-harriet-golden
View
227
Download
6
Embed Size (px)
Citation preview
Chapter 6. Introduction to Trees
Internet Computing Laboratory @ KUT
Youn-Hee Han
1. Basic Tree Concepts
Logical structures
Linear list Tree Graph
Linear structures Non-linear structures
Chap. 6~10 Chap. 11Chap. 3~5
Data Structure3
1. Basic Tree Concepts
선형 자료 구조 리스트 , 스택 , 큐가 데이터 집합을 한 줄로 늘어 세운 선형 자료구조
비선형 자료 구조 트리 (Tree) 는 데이터 집합을 여러 갈래로 나누어 세운 비 선형 구조 비선형 구조 고안 동기
효율성 삽입 , 삭제 , 검색에 대해서 선형 구조보다 나은 시간적 효율을 보임
Data Structure4
1. Basic Tree ConceptsTree consists of
A finite set of nodes (vertices) A finite set of branches (edges, arcs) that connects the
nodes Degree of a node: # of branches
In-degree: # of branch toward the node (# of upward branch) Out-degree: # of branch away from the node (# of downward
branch) Every non-empty tree has a root node whose in-degree
is zero. In-degree of all other nodes is 1
Data Structure5
1. Basic Tree ConceptsDefinitions
트리의 구성 요소에 해당하는 A, B, C, ..., F 를 노드 (Node) 라 함 . A node is child of its predecessor
B 의 바로 아래 있는 E, F 를 B 의 자식노드 (Child Node) 라 함 . A node is parent of its successor nodes
B 는 E, F 의 부모노드 (Parent Node) A 는 B, C, D 의 부모노드 (Parent Node) 임 .
주어진 노드의 상위에 있는 노드들을 조상노드 (Ancestor Node) 라 함 .
B, A 는 F 의 조상노드임 . 어떤 노드의 하위에 있는 노드를 후손노드 (Descendant Node) 라
함 . B, E, F, C, D 는 A 의 후손노드임 .
Path a sequence of nodes in which each node
is adjacent to the next one
Data Structure6
1. Basic Tree ConceptsDefinitions
자매노드 (Sibling Node): nodes with the same parent 같은 부모 아래 자식 사이에 서로를 자매노드 (Sibling Node) 라 함 . B, C, D 는 서로 자매노드이며 , E, F 도 서로 자매노드임 .
부모가 없는 노드 즉 , 원조격인 노드를 루트 노드 (Root Node) 라 함 . C, D, E, F 처럼 자식이 없는 노드를 리프노드 (Leaf Node) 라 함 .
리프노드를 터미널 노드 (Terminal Node) 라고도 함 . node with out-degree zero
리프노드 및 루트노드를 제외한 모든 노드를 내부노드 (Internal Node) 라 함
Data Structure7
1. Basic Tree ConceptsDefinitions
트리의 레벨 (Level) distance from the root 루트노드를 레벨 0 으로 하고 아래로 내려오면서 증가
트리의 높이 (Height or Depth) level of the leaf in the longest path from the root + 1 ( 트리의 최대 레벨 수 + 1) = 트리의 높이 (Height) 루트만 있는 트리의 높이는 1 비어있는 트리 (empty tree) 의 높이는 0
(=4)
Data Structure8
1. Basic Tree ConceptsDefinitions
서브트리 (Subtree): any connected structure below the root 주어진 트리의 부분집합을 이루는 트리를 서브트리 (Subtree) 라 함 .
서브트리는 임의의 노드와 그 노드에 달린 모든 후손노드 (Descendant Node) 를 합한 것임 .
임의의 트리에는 여러 개의 서브트리가 존재할 수 있음 . B, E, F 가 하나의 서브트리 Subtree B C 자체로서도 하나의 서브트리 Subtree C
Subtree B can be divided into two subtrees, C and D
Data Structure9
1. Basic Tree ConceptsRecursive Definitions of Tree
A tree is a set of nodes that either: 1. is Empty, or 2. Has a designated node, called the the root, from which
hierarchically descend zero or more subtrees, which are also trees.
User RepresentationsGeneral tree
Parenthetical listing
Indented list
A (B (C D) E F (G H I) )
Data Structure10
1. Basic Tree Concepts트리의 높이 (Height) 에 대한 다른 정의
1 + 루트노드에서 가장 먼 리프노드까지의 연결 링크 (Link) 개수
트리의 높이 (Height) 에 대한 재귀적 정의 트리의 높이
= 1 + Max{ 왼쪽 서브트리의 높이 , 오른쪽 서브트리의 높이 }
Height 3
Height 1
Height 4
Data Structure11
2. Binary TreeDefinitions
임의의 노드가 둘 이상의 자식노드를 가지는 트리를 일반트리 (General Tree) 라 함 .
임의의 노드가 최대 두 개까지의 자식노드를 가질 수 있는 트리를 이진트리 (Binary Tree) 라 함 .
a tree in which no node can have more than two subtrees the child nodes are called left and right Left/right subtrees are also binary trees
Data Structure12
2. Binary Tree이진트리의 재귀적 정의 (Recursive Definition)
1) 아무런 노드가 없는 트리이거나 , 2) 가운데 노드를 중심으로 좌우로 나뉘되 , 좌우 서브트리 (Subtree)
모두 이진트리다 .
1) 번 때문에 , 아무런 노드가 없는 트리도
주어진 트리의 서브트리이며 동시에 이진트리가 됨 .
1) 번은 재귀호출의 Base-case 에 해당
Data Structure13
2. Binary TreeExamples of Binary Trees
Data Structure14
2. Binary TreeProperties of Binary Tree
가정 (Assumption): 트리 내의 노드의 수 : Maximum Hight
Ex] Given N=3 in a binary tree, what is the maximum hight? Minimum Hight
Ex] Given N=3 in a binary tree, what is the minimum hight?
가정 (Assumption): 트리의 높이 : Maximum Nodes
Ex] Given H=3 in a binary tree, what is the maximum numbers of nodes?
Minimum Nodes
Ex] Given H=3 in a binary tree, what is the minimum numbers of nodes?
N
NHmax
1 NlogH 2min
H
HNmin
12max HN
Data Structure15
2. Binary TreeDefinitions
삼진트리 (Ternary Tree)
Data Structure16
2. Binary TreeBalance
검색에 있어서 다음 어느 Tree 가 효율이 더 좋을까 ? 높이가 3 인 Tree 높이가 2 인 Tree
The shorter the tree, the easier it is to locate any desired node in the tree
Balance Factor : the height of the left subtree : the heighr of the right subtree Balance Factor
Balanced Binary Tree A tree with |B| 1
LH
RH
RL HHB
HL HR
Data Structure17
2. Binary TreeComplete Binary Tree ( 완벽 이진트리 )
높이가 h 인 이진트리에서 모든 리프노드가 레벨 h-1 에 있는 트리 리프노드 위쪽의 모든 노드는 반드시 두개의 자식노드를 거느려야 함 . 시각적으로 볼 때 포화될 정도로 다 차 들어간 모습 . A bianary tree with the maximum # of entries for its height A binary tree in which all leaves (vertices with zero children)
are at the same depth
Complete binary tree 의 Height 가 H 일 때 node 의 갯수가 12max HN
Data Structure18
2. Binary TreeNearly Complete Binary Tree
레벨 (L-1) 까지는 완벽 이진트리 마지막 레벨 L 에서 왼쪽에서 오른쪽으로 가면서 리프노드가 채워짐 .
하나라도 건너뛰고 채워지면 안됨 . Complete Binary Tree 이면 Nearly Complete Binary Tree 이
다 . 그러나 역은 성립 안 됨 .
Complete binary tree 의 노드의 수가 N 일 때 height 는 1 NlogH 2min
Data Structure19
2. Binary Tree – Binary Tree Traversal
Binary Tree Traversal process each node once and only once in a
predetermined sequence Two general approach
Depth-first traversal (depth-first search: DFS) Breadth-first traversal (breadth-first search: BFS, level-
order)
1
4 6
2 5
73
1
5 6
2 3
74
depth-first traversal breadth-first traversal
Data Structure20
2. Binary Tree – Binary Tree Traversal
Depth-first traversal The processing proceeds along a path from the root
through one child to the most distant descendent of that first child before processing a second child.
Preorder traversal (NLR) Root left subtree right subtree
Inorder traversal (LNR) Left subtree root right subtree
Postorder traversal (LRN) Left subtree right subtree root
Data Structure21
2. Binary Tree – Binary Tree Traversal
Depth-first traversal Preorder traversal (NLR) – 1/2
void preOrder(root) {if (root == NULL) return;printf("%s", root->data);preOrder(root->left);preOrder(root->right);
}
Data Structure22
2. Binary Tree – Binary Tree Traversal
Depth-first traversal Preorder traversal (NLR) – 2/2
void preOrder(root) {if (root == NULL) return;printf("%s", root->data);preOrder(root->left);preOrder(root->right);
}
Data Structure23
2. Binary Tree – Binary Tree Traversal
Depth-first traversal Inorder traversal (LNR)
void inOrder(root) {if (root == NULL) return;inOrder(root->left);
printf("%s", root->data);inOrder(root->right);
}
Data Structure24
2. Binary Tree – Binary Tree Traversal
Depth-first traversal Postorder traversal (LRN)
void postOrder(root) {if (root == NULL) return;postOrder(root->left);postOrder(root->right);
printf("%s", root->data);}
Data Structure25
2. Binary Tree – Binary Tree Traversal
Breadth-first traversal (=level-order traversal) Begins at the root node and explores all the neighboring
nodes Then for each of those nearest nodes, it explores their
unexplored neighbor nodes, and so on, until it finds the goal
Attempts to visit the node closest to the root that it has not already visited
Data Structure26
2. Binary Tree – Binary Tree Traversal
Breadth-first traversal (=level-order traversal)void BForder(TreeNode *root) { QUEUE *queue = NULL; TreeNode *node = root; if (node == NULL) return; queue = createQueue(); while(node){
process(node->data); if(node->left) enqueue(queue, node->left); if(node->right) enqueue(queue, node->right); if(!emptyQueue(queue)) dequeue(queue, (void**)&node); else node = NULL; } destroyQueue(queue);}
Data Structure27
2. Binary Tree – Tree ExamplesExpression Tree: a binary tree in which
Each leaf is an operand Root and internal nodes are operators Subtrees are sub-expressions with root being an
operator Traversal Methods
Infix, Postfix, Prefix
Data Structure28
2. Binary Tree – Tree ExamplesInfix Traversal in Expression Tree
void infix(TreeNode *root) {if(root == NULL)
return;if(root->left == NULL && root->right == NULL) printf("%s", root->data);else { printf("("); infix(root->left); printf("%s", root->data); infix(root->right); printf(")");}
}
Data Structure29
2. Binary Tree – Tree ExamplesPostfix Traversal in Expression Tree
void postfix(TreeNode *root) {if(root == NULL)
return;postfix(root->left);postfix(root->right);printf("%s", root->data);
}
abc+*d+
Data Structure30
2. Binary Tree – Tree ExamplesPrefix Traversal in Expression Tree
void prefix(TreeNode *root) {if(root == NULL)
return;printf("%s", root->data);prefix(root->left);prefix(root->right);
}
+*a+bcd
Data Structure31
2. Binary Tree – Tree ExamplesHuffman Code
Representation of characters in computer 7 bits/char (ASCII) 2 bytes/char (KSC Hangul) 2 bytes/char (UNICODE) Isn’t there more efficient way to store text?
Data compression based on frequency Huffman Code Variable length coding Assign short code for characters used frequently
In a text, the frequency of the character E is 15%, and the frequency of the character T is 12%
Data Structure32
2. Binary Tree – Tree ExamplesHuffman Code
Building Huffman tree1. Organize entire character node in a row, ordered by
frequency2. Repeat until all nodes are
connected into “One Binary Tree” Find two nodes with the lowest
frequencies Merge them and make a binary
sybtree Mark the merged frequency into
the root of the subtree
3. End of repeat
Data Structure33
2. Binary Tree – Tree ExamplesHuffman Code
Building Huffman tree
Huffman Tree
Data Structure34
2. Binary Tree – Tree ExamplesHuffman Code
Getting Huffman code from Huffman tree Assign code to each character according to the path from
root to the character
Properties of Huffman code The more frequently used a character, the shorter its code is No code is a prefix of other code
Data Structure35
2. Binary Tree – Tree ExamplesHuffman Code
Data Encoding for communication AGOODMARKET (11 char. * 7 bits = 77 bits) 00011010001001011111000000101011011100111
(42bits)
Decoding 00011010001001011111000000101011011100111 AGOODMARKET
Data Structure36
2. Binary Tree – Tree ExamplesHuffman Code
Another Example문 자문 자 빈 도빈 도
AA 22
BB 1818
CC 99
DD 3030
EE 99
FF 3636
104
38 66
20
11
B
E
A C
D F
A = 0110
B = 00
C = 0111
D = 10
E = 010
F = 11
문 자문 자 빈 도빈 도 원래 크기원래 크기 압축된 크기압축된 크기 차이차이
AA 22 7*2=147*2=14 4*2=84*2=8 66
BB 1818 7*18=1267*18=126 2*18=362*18=36 9090
CC 99 7*9=637*9=63 4*9=364*9=36 2727
DD 3030 7*30=2107*30=210 2*30=602*30=60 150150
EE 99 7*9=637*9=63 3*9=273*9=27 3636
FF 3636 7*36=2527*36=252 2*36=722*36=72 180180
계계 104104 728728 240240 488488
Data Structure37
3. General TreeGeneral Tree
a tree in which each node can have an unlimited out-degree
Data Structure38
3. General TreeInsertion in General Tree
FIFO insertion For a given parent node, insert the new node at the end of
sibling list
LIFO insertion For a given parent node, insert the new node at the
beginning of sibling list
Data Structure39
3. General TreeInsertion in General Tree
Key-sequenced insertion places the new node in key sequence among the sibling
nodes Most common of the insertion rules in general tree Similar to the insertion rule in a general ordered linked list
Data Structure40
3. General TreeDeletion in General Tree
Deletion of only leaf node A node cannot be deleted if it has any children
Other rules for deletion…
Data Structure41
3. General TreeGeneral Tree to Binary Tree
A general tree can be represented by a binary tree 변환 이유
Ex] 일반트리에서는 자식노드의 수가 몇 개가 있는지 예측 불가 변환 방법
부모노드 (Parent Node) 는 무조건 첫 자식노드 (First Child Node) 를 가리킴
첫 자식노드로 (First Child Node) 부터 일렬로 자매 노드 (Sibling Node)들을 연결
Data Structure42
3. General TreeGeneral Tree to Binary Tree