Survey
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
Chapter 6. Introduction to Trees
[INA240] Data Structures and Practice
Youn-Hee Han
http://link.kut.ac.kr
1. Basic Tree Concepts
Logical structures
Chap. 3~5
Chap. 6~10
Chap. 11
Linear list
Tree
Graph
Linear structures
Non-linear structures
1. Basic Tree Concepts
선형 자료 구조
리스트, 스택, 큐가 데이터 집합을 한 줄로 늘어 세운 선형 자료구조
비선형 자료 구조
트리(Tree)는 데이터 집합을 여러 갈래로 나누어 세운 비 선형 구조
비선형 구조 고안 동기
효율성
3
삽입, 삭제, 검색에 대해서 선형 구조보다 나은 시간적 효율을 보임
Data Structure
1. Basic Tree Concepts
Tree 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
4
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 except the root node is one.
Data Structure
1. Basic Tree Concepts
Definitions
트리의 구성 요소에 해당하는 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)임.
어떤 노드의 하위에 있는 노드를 후손노드 (Descendant Node)라 함.
B, E, F, C, D는 A의 후손노드임.
주어진 노드의 상위에 있는 노드들을 조상노드 (Ancestor Node)라 함.
B, A는 F의 조상노드임.
Path
a sequence of nodes in which each node
is adjacent to the next one
5
Data Structure
1. Basic Tree Concepts
Definitions
자매노드 (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)라 함
B
6
Data Structure
1. Basic Tree Concepts
Definitions
트리의 레벨(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)
7
Data Structure
1. Basic Tree Concepts
Definitions
서브트리 (Subtree)
주어진 트리의 부분집합을 이루는 트리를 서브트리 (Subtree)라 함.
서브트리는 임의의 노드와 그 노드에 달린 모든 후손노드 (Descendant
Node) 를 합한 것임.
임의의 트리에는 여러 개의 서브트리가 존재할 수 있음.
8
B, E, F가 하나의 서브트리 Subtree B
C 자체로서도 하나의 서브트리 Subtree C
Data Structure
1. Basic Tree Concepts
Definitions
서브트리 (Subtree)
Subtree B can be
divided into two
subtrees, C and D
9
Data Structure
1. Basic Tree Concepts
Recursive 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 Representations
General tree
Indented list
Parenthetical listing
A (B (C D) E F (G H I) )
10
Data Structure
1. Basic Tree Concepts
트리의 높이(Height)에 대한 다른 정의
1 + 루트노드에서 가장 먼 리프노드까지의 연결 링크(Link) 개수
트리의 높이(Height)에 대한 재귀적 정의
트리의 높이
= 1 + Max{왼쪽 서브트리의 높이, 오른쪽 서브트리의 높이}
Height 3
Height 1
Height 4
11
Data Structure
2. Binary Tree
General Tree
임의의 임의의 노드가 둘 이상의 자식노드를 가지는 트리를 일반트리
(General Tree)라 함.
Binary Tree
임의의 노드가 최대 두 개까지의 자식노드를 가질 수 있는 트리를 이진트리
(Binary Tree)라 함.
12
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 Structure
2. Binary Tree
이진트리의 재귀적 정의 (Recursive Definition)
1) 아무런 노드가 없는 트리이거나,
2) 가운데 노드를 중심으로 좌우로 나뉘되, 좌우 서브트리 (Subtree)
모두 이진트리다.
1)번 때문에,
아무런 노드가 없는 트리도
주어진 트리의 서브트리이며
동시에 이진트리가 됨.
1)번은 재귀호출의 Base-case에 해당
13
Data Structure
2. Binary Tree
Examples of Binary Trees
14
Data Structure
2. Binary Tree
Properties of Binary Tree
트리 내의 노드의 수를 N 이라 가정했을 때
Maximum Height
Ex] Given N=3 in a binary tree, what is the maximum height?
Minimum Height
H max N
H min log 2 N 1
Ex] Given N=3 in a binary tree, what is the minimum height?
트리의 높이를 H 라고 가정했을 때
Maximum Number of Nodes
N max 2 H 1
Ex] Given H=3 in a binary tree, what is the maximum number of nodes?
Minimum Number of Nodes
N min H
15
Ex] Given H=3 in a binary tree, what is the minimum number of nodes?
Data Structure
2. Binary Tree
Definitions
16
삼진트리 (Ternary Tree)
Data Structure
2. Binary Tree
Balance
검색에 있어서 다음 어느 Tree 가 효율이 더 좋을까?
높이가 3인 Tree
높이가 2인 Tree
The shorter the tree, the easier it is to locate any desired node in the
tree
Balance Factor
H L : the height of the left subtree
H R: the height of the right subtree
Balance Factor
B HL HR
Balanced Binary Tree
A tree with |B| 1
HL
17
HR
Data Structure
2. Binary Tree
Complete 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
H
Complete binary tree의 Height가 H 일 때 node의 갯수가 N max 2 1
18
Data Structure
2. Binary Tree
Nearly Complete Binary Tree
레벨 (L-1)까지는 완벽 이진트리
마지막 레벨 L에서 왼쪽에서 오른쪽으로 가면서 리프노드가 채워짐.
하나라도 건너뛰고 채워지면 안됨.
Complete Binary Tree 이면 Nearly Complete Binary Tree 이다. 그러나
역은 성립 안 됨.
Complete binary tree의 노드의 수가 N 일 때 height는 H min log 2 N 1
19
Data Structure
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
1
5
2
3
4
6
depth-first traversal
20
3
2
7
4
5
6
7
breadth-first traversal
Data Structure
2. Binary Tree – Binary Tree Traversal
Depth-first traversal (Depth-first search, DFS)
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.
세가지 DFS 방법
Preorder traversal (NLR)
Root left subtree right subtree
Inorder traversal (LNR)
Left subtree root right subtree
Postorder traversal (LRN)
Left subtree right subtree root
21
Data Structure
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);
}
22
Data Structure
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);
}
23
Data Structure
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);
}
24
Data Structure
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);
}
25
Data Structure
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
26
Data Structure
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);
}
27
Data Structure
2. Binary Tree – Tree Examples
Expression 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
28
Data Structure
2. Binary Tree – Tree Examples
Infix 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(")");
}
}
29
Data Structure
2. Binary Tree – Tree Examples
Postfix Traversal in Expression Tree
void postfix(TreeNode *root) {
if(root == NULL)
return;
postfix(root->left);
postfix(root->right);
printf("%s", root->data);
}
abc+*d+
30
Data Structure
2. Binary Tree – Tree Examples
Prefix Traversal in Expression Tree
void prefix(TreeNode *root) {
if(root == NULL)
return;
printf("%s", root->data);
prefix(root->left);
prefix(root->right);
}
+*a+bcd
31
Data Structure
2. Binary Tree – Tree Examples
Huffman 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%
32
Data Structure
2. Binary Tree – Tree Examples
Huffman Code
Building Huffman tree
1. Organize entire character node in a row, ordered by frequency
2. 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
33
Data Structure
2. Binary Tree – Tree Examples
Huffman Code
Building Huffman tree
Huffman Tree
34
Data Structure
2. Binary Tree – Tree Examples
Huffman 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
35
Data Structure
2. Binary Tree – Tree Examples
Huffman Code
Data Encoding for communication
AGOODMARKET (11 char. * 7 bits = 77 bits)
00011010001001011111000000101011011100111 (42bits)
Decoding
00011010001001011111000000101011011100111
AGOODMARKET
36
Data Structure
2. Binary Tree – Tree Examples
Huffman Code
37
Another Example
문자
빈도
A
2
B
18
C
9
D
30
E
9
F
36
104
66
38
A = 0110
B
D
20
F
B = 00
C = 0111
D = 10
11
E
E = 010
F = 11
A
C
문자
빈도
원래 크기
압축된 크기
차이
A
2
7*2=14
4*2=8
6
B
18
7*18=126
2*18=36
90
C
9
7*9=63
4*9=36
27
D
30
7*30=210
2*30=60
150
E
9
7*9=63
3*9=27
36
F
36
7*36=252
2*36=72
180
계
104
728
240
488
Data Structure
3. General Tree
General Tree
38
a tree in which each node can have an unlimited out-degree
Data Structure
3. General Tree
Insertion 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
39
Data Structure
3. General Tree
Insertion 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
40
Data Structure
3. General Tree
Deletion in General Tree
Deletion of only leaf node
A node cannot be deleted if it has any children
41
Other rules for deletion…
Data Structure
3. General Tree
General 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)들을
연결
42
Data Structure
3. General Tree
General Tree to Binary Tree
43
Data Structure