Unit 4
Unit 4
Tree
s
Tree
s Root
Dusty
Honey Brandy
Bear
Brunhilde Terry Coyote Nugget
leaf
2
Definition of Tree
A treeis a finite set of one or more
nodes such that:
– There is a specially designated node called
the root.
– The remaining nodes are partitioned into n>=0 disjoint
sets T1, ..., Tn, where each of these sets is a tree.
– We call T1, ..., Tn the subtrees of the root.
3
Level and Depth
Level
1. node (13) A
2. leaf (terminal) 3 1 1
3. nonterminal
4. parent B 2 1 C 2 3 D 2
5. children 2 2
6. sibling
E G H I J 3 3
7. degree of a tree (3)
F 0 30
8. ancestor 2 30 3 31 30
9. level of a node
10. height of a tree L M 4
0 K4 0 4 0 4
(4)
4
Terminology
The degree of a node is the number of
subtrees of the node
– The degree of A is 3; the degree of C is 1.
The node with degree 0 is a leaf or
terminal node.
A node that has subtrees is the parent of
the subtrees.
These subtrees are the children
of the node.
Children of the same parent are
siblings.
along the path of
The ancestors from the root
a node to the
are all 5
Representation of Trees
List Representation
– ( A ( B ( E ( K, L ), F ), C ( G ), D ( H ( M ), I, J ) ) )
– The root comes first, followed by a list of sub-trees
6
Left Child - Right Sibling
data
A left child right sibling
B C D
E F G H I J
K L M
7
Binary Trees
E C
F G D
K
H
L
M I
10
Abstract Data Type Binary_Tree
11
Samples of Trees
Complete Binary Tree
A A 1 A
B B 2 B C
C
3 D E F G
Skewed Binary Tree
D
4 H I
E 5
12
Maximum Number of Nodes in BT
Prove by induction.
k 2i 1 2 k
i 1
pp. 200
1
13
Relations between Number of
Leaf Nodes and Nodes of Degree 2
For any nonempty binary tree, T, if n0 is the
number of leaf nodes and n2 the number of nodes
of degree 2, then n0=n2+1
proof:
Let n and B denote the total number of nodes &
branches in T.
Let n0, n1, n2 represent the nodes with no children,
D E F G D E F G
O
H I H I J K L M N
Complete binary tree Full binary tree of depth
15
Binary Tree Representations
H I 17
Linked Representation
typedef struct node *tree_pointer;
typedef struct node {
int data;
tree_pointer left_child,
right_child;
};
data
left_child data right_child
left_child right_child
18
Binary Tree Traversals
* E preorder traversal
+ * * / ABC D
E prefix
* D expression
postorder traversal
/ C AB / C * D* E +
postfix
expression
A B
level order traversal
+*E*D/CAB
20
Inorder Traversal (recursive version)
void inorder(tree_pointer ptr)
/* inorder tree traversal */
{
A/ B* C * D+ E
if (ptr) {
inorder(ptr->left_child);
printf(“%d”, ptr->data);
inorder(ptr->right_child);
}
} 21
Preorder Traversal (recursive
version)
void preorder(tree_pointer ptr)
/* preorder tree traversal */
{
+ * * / ABC D E
if (ptr) {
printf(“%d”, ptr->data);
preorder(ptr->left_child);
preorder(ptr->right_child);
}
} 22
Postorder Traversal (recursive
version)
void postorder(tree_pointer ptr)
/* postorder tree traversal */
{
AB / C* D * E +
if (ptr) {
postorder(ptr->left_child);
postorder(ptr->right_child);
printf(“%d”, ptr->data);
}
} 23
Iterative Inorder Traversal
(using stack)
void iterInorder(tree_pointer node)
{
int top= -1; /* initialize stack */
tree_pointer
stack[MAX_STACK_SIZE]; for (;;) {
for (; node; node=node-
>left_child)
push(&top, node);/* add to stack */
node= pop(&top);
/* delete from stack
*/
if (!node) break; /* empty stack
} */ printf(“%D”, node->data);
node = O(n)
node->right_child; LV
} R
Trace Operations of Inorder Traversal
Call of inorder Value in root Action Call of inorder Value in root Action
1 + 11 C
2 * 12 NULL
3 * 11 C printf
4 / 13 NULL
5 A 2 * printf
6 NULL 14 D
5 A 15 NULL
printf
7 NULL 14 D printf
4 / 16 NULL
printf
8 B 1 + printf
9 NULL 17 E
8 B 18 NULL
25
LV
Level Order Traversal
(using queue)
26
if (ptr) {
printf(“%d”, ptr->data);
if (ptr->left_child)
addq(ptr->left_child);
if (ptr->right_child)
addq(ptr-
>right_child);
}
else break;
}
} +*E*D/CAB
27
Traversing a binary tree
前序走訪 (preorder):
40 95 65 70 98
40
17
22
17 95
22 65 98
70
Traversing a binary tree
中序走訪 (inorder):
17 65 70 95 98
40
22
40
17 95
22 65 98
70
Traversing a binary tree
後序走訪 (postorder):
22 65 98 95 40
40
17
70
17 95
22 65 98
70
Traversing a binaryqueuetree
階層走訪 (level-order): 17 95 22 65 98 70
40
95 22 65 98 70
40 40 17
17 95
22 65 98
70
Copying Binary Trees
tree_pointer copy(tree_pointer original)
{
tree_pointer temp;
if (original) {
temp=(tree_pointer) malloc(sizeof(node));
if (IS_FULL(temp)) {
fprintf(stderr, “the memory is full\n”);
exit(1);
}
temp->left_child=copy(original->left_child);
temp->right_child=copy(original->right_child);
temp->data=original->data;
return temp;
}
return NULL;
} postorder
32
Equality of Binary Trees
the same topology and data
int equal(tree_pointer first, tree_pointer second)
{
/* function returns FALSE if the binary trees first
and second are not equal, otherwise it returns TRUE
*/
return ((!first && !second) || (first && second &&
(first->data == second->data) &&
equal(first->left_child, second->left_child) &&
equal(first->right_child, second->right_child))
}
33
Propositional Calculus Expression
A variable is an expression.
If x and y are expressions, then ¬x,
xy, xy are expressions.
Parentheses can be used to alter the
normal order of evaluation (¬ > > ).
Example: x1 (x2 ¬x3)
satisfiability
problem: Is there an
assignment to make an expression
true? 34
(x1 ¬x2) (¬ x1 x3) ¬x3
(t,t,t)
(t,t,f)
(t,f,t)
(t,f,f)
(f,t,t) X3
(f,t,f)
(f,f,t) X1 X3
(f,f,f)
2n possible combinations X2 X1
for n variables
postorder traversal (postfix evaluation)
LRV
Node Structure
left_child data value right_child
40
Threaded Binary Trees
(Continued)
If ptr->left_child is null,
replace it with a pointer to the node that would be
visited before ptr in an inorder traversal
If ptr->right_child is null,
replace it with a pointer to the node that would be
visited after ptr in an inorder traversal
41
A Threaded Binary Tree
root A
dangling
B C
dangling D E F G
inorder traversal:
H I H, D, I, B, E, A, F, C, G
42
Data Structures for Threaded BT
left_thread left_child data right_child
right_thread
TRUE FALSE
root --
f f
f A f
f B f f C f
f D f t E t t F t t G
t H t t I t
44
Next Node in Threaded BT
threaded_pointer insucc(threaded_pointer
tree)
{
threaded_pointer temp;
temp = tree->right_child;
if (!tree->right_thread)
while (!temp->left_thread)
temp = temp-
>left_child;
return temp;
} 45
Inorder Traversal of Threaded BT
47
Examples
Insert a node D as a right child of B.
empty
root root
A A
(1)
parent parent
B B
(3)
C child C child
D
D (2)
(a)
48
*Figure 5.24: Insertion of child as a right child of parent in a threaded binary
tree
nonempty
(3)
(2) (1)
(4)
Right Insertion in Threaded BTs
void insertRight(threaded_pointer parent,
threaded_pointer child)
{ threaded_pointer temp;
(1)
child->right_child = parent->right_child;
child->right_thread = parent->right_thread;
(2) child->left_child
child->left_thread= =parent;
TRUE; case (a)
(3) parent->right_child = child;
parent->right_thread = FALSE;
if (!child->right_thread) { case (b)
temp = insucc(child);
(4) temp->left_child = child;
}
} 50
Heap
A max tree is a tree in which the key value in
each node is no smaller than the key values in
its children.
– A max heap is a complete binary tree that is also a
max tree.
A min tree is a tree in which the key value in
each node is no larger than the key values in
its children.
– A min heap is a complete binary tree that is also
a min tree.
Operations on heaps
– creation of an empty heap
– insertion of a new element into the heap
– deletion of the largest element from the heap
*Figure 5.25: Max heaps
[1] 9
[1] 14 [1] 30
Property:
The root of max heap (min heap) contains
the largest (smallest).
*Figure 5.26: Min heaps
[1]
2 [1] 10 [1] 11
55
ADT MaxPriorityQuere 是
物件: n 個元素形成的集合 (n > 0) ,每個元素有一個鍵值
函式:對所有的 q∈MaxPriorityQueue , item∈Element , n
是整 數
MaxPriorityQueue ::= 建立一個空的優先權佇列
create(max_size)
Boolean isEmpty(q,n) ::= if(n > 0) return FALSE
else return TRUE
Element top(q,n) ::= if(!isEmpty(q,n)) return q
內 最大的元素
else return 錯誤
Element pop(q,n) ::= if(!isEmpty(q,n)) return q 內
最大的元素並把它從堆積中
移除
else return 錯誤
MaxPriorityQueue ::= 把 item 插入 q 中並回傳優先
push(q,item,n) 權佇列的結果
56
Data Structures
unordered linked
list
unordered array
sorted array
heap
57
*Figure 5.27: Priority queue representations
20 20 21
15 2 15 5 15 20
14 10 14 10 2 14 10 2
initial location of new node insert 5 into heap insert 21 into heap
59
Insertion into a Max Heap
void push(element item, int *n)
{/* 把項目加入目前大小是 n 的最大堆積
*/
int i;
if (HEAP_FULL(*n)) {
O(log2n)
fprintf(stderr, “the heap is full.\n”);
exit(1);
}
i = ++(*n);
while ((i!=1)&&(item.key>heap[i/2].key)) {
heap[i] = heap[i/2]; // moving up to root
i /= 2;
}
heap[i]= item;
2 k-1=n ==> k=log (n+1)
2
}
60
Example of Deletion from Max Heap
remove
20 10 15
15 2 15 2 14 2
14 10 14 10
61
Deletion from a Max Heap
element pop(int *n)
{/* 從堆積中刪除鍵最高的元素
*/ int parent, child;
element item, temp;
if (HEAP_EMPTY(*n)) {
fprintf(stderr, “The heap is empty\n”);
exit(1);
}
/* save value of the element with the
highest key */
item = heap[1];
/* use last element in heap to adjust heap */
temp = heap[(*n)--];
parent = 1;
child = 2; 62
while (child <= *n) {
/* find the larger child of the current
parent */
if ((child < *n)&&
(heap[child].key<heap[child+1].key))
child++;
if (temp.key >= heap[child].key) break;
/* move to the next lower level */
heap[parent] = heap[child];
head = child;
child *= 2;
}
heap[parent] = temp;
return item;
}
63
ADT Dictionary 是
物件: n 個資料對形成的集合 (n > 0) ,每個資料對有一個鍵值和
搭配 的項目
函式:
對於所有的 d∈Dictionary , item∈Item , k∈Key , n 是整數
Dictionary Create(max_size) ::= 建立一個空的字典
64
Binary Search Tree
Heap
– a min (max) element is deleted. O(log2n)
– deletion of an arbitrary element O(n)
– search for an arbitrary element O(n)
Binary search tree
– Every element has a unique key.
– The keys in a nonempty left subtree (right
subtree) are smaller (larger) than the key in the
root of subtree.
– The left and right subtrees are also binary
search trees.
65
Examples of Binary Search Trees
20 30 60
12 25 5 40 70
10 15 22 2 65 80
66
Searching a Binary Search Tree
tree_pointer search(tree_pointer root,
int key)
{
/* return a pointer to the node that
contains key. If there is no such
node, return NULL */
30 30 30
5 40 5 40 5 40
2 2 80 2 35 80
Insert 80 Insert 35
69
void
Insertion into a Binary Search Tree
insert(tree_pointer *node, int k, iType
theItem)
{tree_pointer ptr,
temp = modified_search(*node, k);
if (temp || !(*node)) {/* k 不在樹中 */
ptr = (tree_pointer)
malloc(sizeof(node));
if (IS_FULL(ptr)) {
fprintf(stderr, “The memory is full\
n”); exit(1);
}
ptr->data.key = k; ptr->data.item =
theItem; ptr->left_child = ptr->right_child
= NULL; if (*node)
if (k < temp->data) temp->left_child=ptr;
else temp->right_child = ptr;
else *node = ptr;
70
}
Binary search tree insert and
search
用 list 的方式實作 binary search tree 的插
入 和搜尋
實作步驟
1. 建立樹的 node 結構 (struct)
2. 建立一棵 binary search tree
3. 主要 function
– 插入 : insertNode()
– 搜尋 : searchNode()
Binary search tree insert and
search
建立一棵 binary search
tree
40
22 65 98
70
Binary search tree insert and
search
插入 40
20 20 < 40
17 95
20 > 17
22 65 98
20 < 22
20 70
Binary search tree insert and
search
搜尋 40
70 70 > 40
17 95
70 < 95
22 65 98
70 > 65
20 70
Binary search tree insert and
search
建立樹的 node 結構
(struct)
Binary search tree insert and
search
插入 :
insertNode()
Binary search tree insert and
search
插入 :
insertNode()
Binary search tree insert and
search
搜尋 :
searchNode()
Deletion for a Binary Search Tree
5 5
5 40 2 40
2 80 80
(a) (b)
79
Deletion for a Binary Search Tree
40 non-leaf 40
node
20 60 20 55
10 30 50 70 10 30 50 70
45 55 45 52
52
Before deleting 60 After deleting 60 In the left, to
find the maximum
In the right, to find the minmum
80
Split a Binary Search Tree
void split (nodePointer *theTree, int k, nodePointer *samll,
element *mid, nodePointer *big)
{ /* 根據鍵 k 來分割二元搜尋樹 */
if (!theTree) {*small = *big = 0; (*mid).key = -1;
return;}
/* 空樹 */
nodePointer sHead, bHead, s, b, currentNode;
/* 替 small 和 big 建立標頭節點 */
MALLOC(sHead, sizeof(*sHead));
MALLOC(bHead, sizeof(*bHead));
s = sHead, b = bHead;
/* 執行分割 */
currentNode = *theTree;
81
while (currentNode)
if (k < currentNode→data.key) { /* 加到 big
*/ b→leftChild = currentNode; b =
currentNode; currentNode =
currentNode→leftChild; }
else if (k > currentNode→data.key) { /* 加到
small */
s→rightChild = currentNode; s = currentNode;
currentNode = currentNode→rightChild; }
else { /* 在 currentNode 做 分 割 */
s→rightChild = currentNode→leftChild;
b→leftChild =
currentNode→rightChild;
*small = sHead→rightChild;
free(sHead);
*big = bHead→leftChild; free(bHead);
82
(*mid).item =
/* 沒有鍵為 k 的字典對 */
s→rightChild = b→leftChild = 0;
*small = sHead→rightChild; free(sHead);
*big = bHead→leftChild; free(bHead);
(*mid).key = -1;
return;
}
83
Selection Trees
(1) Winner tree
(2) Loser tree
84
Each node represents
Sequential allocation
scheme
Winner tree the smaller of its two
1 children.
(complete binary
6
tree)
2 3
6 8
4 5 6 7
9 6 8 17
8 9 10 11 14 15
12 13
10 9 20 6 9 90 17
8
ordered sequence
15 20 20 15 15 11 10 18
16 38 30 25 50 16 0 20
11
0
4 5 6 7
9 15 8 17
8 9 10 11 12 13 14 15
10 9 20 15 8 9 90 17
15 20 20 25 15 11 100 18
16 38 30 25 50 16 110 20
Analysis
K: # of runs
n: # of records
O(K)
restructure time: O(log2K) log2(K+1)
87
*Figure 5.34: Tree of losers corresponding to Figure 5.32
overall
6
8 winner
9
1
8
2
9 3
9 15 17
4 5 6 7
10 20 15 9 90
8 9 10 11 12 13 14 15
10 9 20 6 8 9 90 17
Run 1 2 3 4 5 6 7 8
15 15
Forest
Definition: A forest is a set of n >= 0 disjoint trees
A
Forest
A E G
B E
B C D F H I C F G
D H
89
Transform a forest into a binary tree
Preorder (VLR)
– If F is empty, then return
– Visit the root of the first tree of F
– Taverse the subtrees of the first tree in tree preorder
– Traverse the remaining trees of F in preorder
Inorder (LVR)
– If F is empty, then return
– Traverse the subtrees of the first tree in tree inorder
– Visit the root of the first tree
– Traverse the remaining trees of F is indorer
91
A inorder: EFBGCHIJDA
preorder:
B ABEFCGDHIJ
A
E C
B C D
F G D
E F J
G H I
H
I
B C
preorder
D
J
E G H
I
F J
92
Set Representation
6 7 8 4 9 3 5
0 1
8 1 0 4 9
6 7
4 9 6 7 8
0
Set Pointer
Name
6 7 8
S1
S2 4
S3 1 9
3 5
Array Representation for Set
i [0] [1] [2] [3] [4] [5] [6] [7] [8] [9]
parent -1 4 -1 2 -1 2 0 0 0 4
int simpleFind(int i)
{
for (; parent[i]>=0; i=parent[i]);
return i;
}
void simpleUnion(int i, int j)
{
parent[i]= j;
}
96
*Figure 5.41:Degenerate tree ( 退化
樹)
degenerate tree
*Figure 5.42:Trees obtained using the weighting rule
• •
1 1
起始狀況 2
Union Union
(0,1) (0,2)
0 4 •• n-1 0
• • •
1 2 • 1 2 3 •• n-1
3 •
Union
(0,3) Union (0,n-1)
Modified Union Operation
void weightedUnion(int i, int j)
{ Keep a count in the root of tree
//parent[i]=-count[i] and parent[i]=-count[j]
int temp = parent[i]+ parent[j];
if (parent[i]>parent[j]) {
parent[i]=j;
/* make j the new root*/
parent[j]=temp;
}
else {
parent[j]=i;
/* make i the new root*/
parent[i]=temp;
} If the number of nodes in tree i is
} less than the number in tree j,
then make j the parent of i;
otherwise make i the parent of j.
[-1] [-1] [-1] [-1] [-1] [-1] [-1] [-1]
0 1 2 3 4 5 6 7
(a) 一 開 始 樹 的 高 度 都 是 1
1 3 5 7
1 2 5 6
[-8]
1 2 4
0
3 5 6
1 2 4 1 2 4 6 7
3 5 6 3 5
102
Application to Equivalence Classes
(a) 起 始 樹
4 1 10 9
(b) 處 理 完 0 ≡ 4, 3 ≡ 1, 6 ≡ 10, 8 ≡ 9 後 高 度 為 2 的
樹
4 7 10 8 1 5 11
(c) 處 理 完 7 ≡ 4, 6 ≡ 8, 3 ≡ 5,
2 ≡ 11 後 的 樹
[-5] [-4] [-3]
0 6 3
4 7 2 10 8 1 5
11 9
(d) 處 理 完 11 ≡ 0 後 的 樹
preorder: ABCD EFGHI
inorder: BCAEDGHF
A I A
B, C D, E, F, G, H, I B D
A
C E F
B D, E, F, G, H, I G I
C H
105