Chapter 3
Chapter 3
Data Structure
Chapter 2 Stack and Queue
3.1 Definition and Concept of Tree
3.2 Tree Terminology
3.3 Types of Binary Tree
3.3.1 Strictly binary trees
3.3.2 Complete binary trees
3.3.3 Extended binary trees
3.4 Binary tree representation
3.5 Creation of Binary tree
Dr Sharad Patil 2
Contd..
3.6 Operations on Binary tree
3.6.1 Traversal of binary tree (inorder, preorder,
postorder )
3.6.2. Non-recursive traversal (preorder, inorder,
postorder)
3.7 Binary search tree
3.7.1 Inseration of nodes
3.7.2 Binary searching for nodes
3.7.3 Deletion a node
3.8 Theraded binary tree
3.9 Height Balance Drtrees
Sharad Patil 3
Trees
Root
Dusty
leaf
CHAPTER 5 4
Definition of Tree
A tree is 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.
CHAPTER 5 5
Level and Depth
Level
node (13)
degree of a node
A 1
leaf (terminal) 3 1
nonterminal
parent B C D
2 2
2 21 2 3
children
sibling E F G H I J 3
2 30 30 31 30 30 3
degree of a tree (3)
ancestor K L M 4
0 40 4 0 4
level of a node
height of a tree (4)
CHAPTER 5 6
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
roots of the subtrees.
The roots of these subtrees are the children of
the node.
Children of the same parent are siblings.
The ancestors of a node are all the nodes
along the path from the5 root to the node. 7
CHAPTER
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
CHAPTER 5 8
Left Child - Right Sibling
data
A left child right sibling
B C D
E F G H I J
K L M
CHAPTER 5 9
Binary Trees
A binary tree is a finite set of nodes that is
either empty or consists of a root and two
disjoint binary trees called the left subtree
and the right subtree.
Any tree can be transformed into binary tree.
– by left child-right sibling representation
The left subtree and the right subtree are
distinguished.
CHAPTER 5 10
*Figure 5.6: Left child-right child tree representation of a tree (p.1
E C
F G D
K
H
L
M I
J
Abstract Data Type Binary_Tree
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 tree
Boolean IsEmpty(bt)::= if (bt==empty binary
tree) return TRUE else return FALSE
CHAPTER 5 12
BinTree MakeBT(bt1, item, bt2)::= return a binary tre
whose left subtree is bt1, whose right subtree is
and whose root node contains the data item
Bintree Lchild(bt)::= if (IsEmpty(bt)) return error
else return the left subtree of bt
element Data(bt)::= if (IsEmpty(bt)) return error
else return the data in the root no
Bintree Rchild(bt)::= if (IsEmpty(bt)) return error
else return the right subtree of bt
CHAPTER 5 13
Samples of Trees
Complete Binary Tree
A A 1 A
B B 2 B C
4 H I
E 5
CHAPTER 5 14
Maximum Number of Nodes in BT
The maximum number of nodes on level i of a
i-1
binary tree is 2i-1, i>=1.
The maximum nubmer of nodes in a binary tree
of depth k is 2k-1, k>=1.
Prove by induction.
k
2 2 1
i 1 k
i 1
CHAPTER 5 15
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,
single child, and two children respectively.
n= n0+n1+n2, B+1=n, B=n1+2n2 ==> n1+2n2+1= n
n1+2n2+1= n0+n1+n2CHAPTER
==>5n0=n2+1 16
Full BT VS Complete BT
A full binary tree of depth k is a binary tree of
k
depth k having 2 -1 nodes, k>=0.
A binary tree with n nodes and depth k is
complete iff its nodes correspond to the nodes
numbered from 1 to n in the full binary tree of
depth k. 由上至下,
A A
由左至右編號
B C B C
D E F G D E F G
H I J K L M N O
H I
Complete binary tree CHAPTER 5 Full binary tree of depth
17 4
Binary Tree Representations
If a complete binary tree with n nodes (depth =
log n + 1) is represented sequentially, then for
any node with index i, 1<=i<=n, we have:
– parent(i) is at i/2 if i!=1. If i=1, i is at the root and
has no parent.
– left_child(i) ia at 2i if 2i<=n. If 2i>n, then i has no
left child.
– right_child(i) ia at 2i+1 if 2i +1 <=n. If 2i +1 >n,
then i has no right child.
CHAPTER 5 18
[1] A
Sequential Representation [2] B
[3] C
(1) waste space
[4] D
(2) insertion/deletion
A [1] A [5] E
[2] B problem
[6] F
[3] -- [7]
B G
[4] C [8]
A H
[5] -- [9]
C I
[6] --
[7] -- B C
D [8] D
[9] --
. . D E F G
E
[16] E
H
CHAPTER 5 I 19
Linked Representation
typedef struct node *tree_pointer;
typedef struct node {
int data;
tree_pointer left_child, right_child;
};
data
CHAPTER 5 20
Binary Tree Traversals
Let L, V, and R stand for moving left, visiting
the node, and moving right.
There are six possible combinations of traversal
– LVR, LRV, VLR, VRL, RVL, RLV
Adopt convention that we traverse left before
right, only 3 traversals remain
– LVR, LRV, VLR
– inorder, postorder, preorder
CHAPTER 5 21
Arithmetic Expression Using BT
+ inorder traversal
A/B*C*D+E
infix expression
* E
preorder traversal
+**/ABCDE
* D prefix expression
postorder traversal
AB/C*D*E+
/ C
postfix expression
level order traversal
A B +*E*D/CAB
CHAPTER 5 22
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);
indorder(ptr->right_child);
}
}
CHAPTER 5 23
Preorder Traversal (recursive version)
void preorder(tree_pointer ptr)
/* preorder tree traversal */
{
+**/ABCDE
if (ptr) {
printf(“%d”, ptr->data);
preorder(ptr->left_child);
predorder(ptr->right_child);
}
}
CHAPTER 5 24
Postorder Traversal (recursive version)
void postorder(tree_pointer ptr)
/* postorder tree traversal */
{
AB/C*D*E+
if (ptr) {
postorder(ptr->left_child);
postdorder(ptr->right_child);
printf(“%d”, ptr->data);
}
}
CHAPTER 5 25
Iterative Inorder Traversal
(using stack)
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);/* add to stack */
node= delete(&top);
/* delete from stack */
if (!node) break; /* empty stack */
printf(“%D”, node->data);
node = node->right_child;
}
} O(n)
CHAPTER 5 26
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 printf 15 NULL
7 NULL 14 D printf
4 / printf 16 NULL
8 B 1 + printf
9 NULL 17 E
8 B printf 18 NULL
10 NULL 17 E printf
3 * printf 19 NULL
CHAPTER 5 27
Level Order Traversal
(using queue)
CHAPTER 5 28
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;
} +*E*D/CAB
}
CHAPTER 5 29
Copying Binary Trees
tree_poointer 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;
} postorder
return NULL;
}
CHAPTER 5 30
Equality of Binary Trees
the same topology and data
CHAPTER 5 31
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 makeCHAPTER 5 an expression 32
(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
node structure
CHAPTER 5 38
Threaded Binary Trees (Continued)
If ptr->left_child is null,
replace it with a pointer to the node that would b
visited before ptr in an inorder traversal
If ptr->right_child is null,
replace it with a pointer to the node that would b
visited after ptr in an inorder traversal
CHAPTER 5 39
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
CHAPTER 5 40
Data Structures for Threaded BT
left_thread left_child data right_child right_threa
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
CHAPTER 5 42
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;
} CHAPTER 5 43
Inorder Traversal of Threaded BT
void tinorder(threaded_pointer tree)
{
/* traverse the threaded binary tree
inorder */
threaded_pointer temp = tree;
for (;;) {
temp = insucc(temp);
O(n) if (temp==tree) break;
printf(“%3c”, temp->data);
}
} CHAPTER 5 44
Inserting Nodes into Threaded BTs
Insert child as the right child of node parent
– change parent->right_thread to FALSE
– set child->left_thread and child->right_thread
to TRUE
– set child->left_child to point to parent
– set child->right_child to parent->right_child
– change parent->right_child to point to child
CHAPTER 5 45
Examples
Insert a node D as a right child of B.
root root
A A
(1)
B parent B parent
(3)
C child child
D C D
(2)
empty
CHAPTER 5 46
*Figure 5.24: Insertion of child as a right child of parent in a threa
(3)
(2) (1)
(4)
nonempty
Right Insertion in Threaded BTs
void insert_right(threaded_pointer parent,
threaded_pointer child)
{
threaded_pointer temp;
child->right_child = parent->right_child;
(1)child->right_thread = parent->right_thread;
child->left_child = parent; case (a)
(2)child->left_thread = TRUE;
parent->right_child = child;
(3)parent->right_thread = FALSE;
if (!child->right_thread) { case (b)
temp = insucc(child);
(4)temp->left_child = child;
}
} CHAPTER 5 48
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
CHAPTER 5
element from the heap 49
*Figure 5.25: Sample max heaps (p.219)
Property:
The root of max heap (min heap) contains
the largest (smallest).
*Figure 5.26:Sample min heaps (p.220)
CHAPTER 5 53
Data Structures
unordered linked list
unordered array
sorted linked list
sorted array
heap
CHAPTER 5 54
*Figure 5.27: Priority queue representations (p.221)
20 20 21
15 2 15 5 15 20
14 10 14 10 2 14 10 2
CHAPTER 5 56
Insertion into a Max Heap
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; 2k-1=n ==> k=log2(n+1)
}
heap[i]= item; O(log2n)
} CHAPTER 5 57
Example of Deletion from Max Heap
remove
20 10 15
15 2 15 2 14 2
14 10 14 10
CHAPTER 5 58
Deletion from a Max Heap
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);
}
/* 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;
CHAPTER 5 59
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];
child *= 2;
}
heap[parent] = temp;
return item;
}
CHAPTER 5 60
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. CHAPTER 5 61
Examples of Binary Search Trees
20 30 60
12 25 5 40 70
10 15 22 2 65 80
CHAPTER 5 62
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
CHAPTER 5 65
Insertion into A Binary Search Tree
void insert_node(tree_pointer *node, int num)
{tree_pointer ptr,
temp = modified_search(*node, num);
if (temp || !(*node)) {
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)
if (num<temp->data) temp->left_child=ptr;
else temp->right_child = ptr;
else *node = ptr;
}
} CHAPTER 5 66
Deletion for A Binary Search Tree
1
leaf 30
node
5 80
T1 T2
1
2
2
T1 X
T2
CHAPTER 5 67
Deletion for A Binary Search Tree
non-leaf
40 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
CHAPTER 5 68
1
2
T1
T2 T3
1
2‘
T1
T2’ T3
CHAPTER 5 69
Selection Trees
(1) winner tree
(2) loser tree
CHAPTER 5 70
sequential Each node represents
allocation winner1 tree the smaller of its two
scheme children.
6
(complete
binary 2 3
tree) 6 8
4 5 6 7
9 6 8 17
8 9 10 11 12 13 14 15
10 9 20 6 8 9 90 17
ordered sequence
15 20 20 15 15 11 100 18
16 38 30 25 50 16 110 20
1
8
2 3
9 8
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
setup time: O(K) (K-1)
restructure time: O(log2K)
log2(K+1)
merge time: O(nlog2K)
slight modification: tree of loser
consider the parent node only (vs. sibling
nodes) CHAPTER 5 73
*Figure 5.36: Tree of losers corresponding to Figure 5.34 (p.23
overall
6 winner
8
9
1
8
9
2 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
15 15
Forest
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
CHAPTER 5 75
Transform a forest into a binary
tree
T1, T2, …, Tn: a forest of trees
B(T1, T2, …, Tn): a binary tree
corresponding to this forest
algorithm
(1) empty, if n = 0
(2) has root equal to root(T1)
has left subtree equal to
B(T11,T12,…,T1m)
has right subtree equal to B(T2,T3,…,Tn)
CHAPTER 5 76
Forest Traversals
Preorder
– 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
– 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
CHAPTER 5 77
A inorder: EFBGCHIJDA
preorder: ABEFCGDHIJ
B
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
F I
J
CHAPTER 5 78
Set Representation
S1={0, 6, 7, 8}, S2={1, 4, 9}, S3={2, 3, 5}
0 1 2
6 7 8 4 9 3 5
Si Sj =
Two operations considered here
– Disjoint set union S1 S2={0,6,7,8,1,4,9}
– Find(i): Find the set containing the element i.
3 S 3, 8 S 1
CHAPTER 5 79
Disjoint Set Union
Make one of trees a subtree of the other
0 1
8 1 0 4 9
6 7
4 9 6 7 8
CHAPTER 5 80
*Figure 5.41:Data Representation of S1S2and S3 (p.240)
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 find1(int i)
{
for (; parent[i]>=0; i=parent[i])
return i;
}
degenerate tree
*Figure 5.44:Trees obtained using the weighting rule(p.243)
ghting rule for union(i,j): if # of nodes in i < # in j then j the parent
Modified Union Operation
void union2(int i, int j)
{ Keep a count in the root of tree
int temp = parent[i]+parent[j];
if (parent[i]>parent[j]) {
parent[i]=j; i has fewer nodes.
parent[j]=temp;
}
else { j has fewer nodes
parent[j]=i;
parent[i]=temp;
} If the number of nodes in tree i is
} less than the number in tree j, the
make j the parent of i; otherwise
make i the parent of j.
CHAPTER 5 85
Figure 5.45:Trees achieving worst case bound (p.245)
log28+1
Modified Find(i) Operation
int find2(int i)
{
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;
} If j is a node on the path from
return root: i to its root then make j a child
} of the root
CHAPTER 5 87
0 0
1 2 4 1 2 4 6 7
3 5 6 3 5
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
CHAPTER 5 90