Unit II - Tree - 1 - Updatedv2
Unit II - Tree - 1 - Updatedv2
3
Syllabus
1. Hashing - Concepts-hash table, hash function, basic operations, bucket, collision, probe, synonym,
overflow, open hashing, closed hashing, perfect hash function, load density, full table, load factor,
rehashing, issues in hashing, hash functions- properties of good hash function, division, multiplication,
extraction, mid-square, folding and universal, Collision resolution strategies- open addressing and chaining,
Hash table overflow- open addressing and chaining.
2. Tree - Basic Terminology, Binary Tree- Properties, Converting Tree to Binary Tree, Representation
using Sequential and Linked organization, Binary tree creation and Traversals, Operations on binary tree.
Binary Search Tree (BST) and its operations,
Threaded binary tree- Creation and Traversal of In-order Threaded Binary tree.
Case Study- Expression tree
3. Graph - Basic Terminology, Graphs (Directed, Undirected), Various Representations, Traversals &
Applications of graph- Prim’s and Kruskal’s Algorithms, Dijsktra's Single source shortest path, Analysis
complexity of algorithm, topological sorting.
4. Heap - Heap as a priority queue, Heap sort. Symbol Table-Representation of Symbol Tables- Static tree
table and Dynamic tree table, Weight balanced tree - Optimal Binary Search Tree (OBST), OBST as an
example of Dynamic Programming, Height Balanced Tree- AVL tree.
Search trees: Red-Black Tree, AA tree, K-dimensional tree, Splay Tree.
5. Multiway search trees, B-Tree - insertion, deletion, B+Tree - insertion, deletion, use of B+ tree in
Indexing, Trie Tree.
Files: concept, need, primitive operations. Sequential file organization - concept and primitive operations,
Direct Access File- Concepts and Primitive operations, Indexed sequential file Organization-concept,
types of indices, structure of index sequential file, Linked Organization - multi list files.
2. Implement binary tree and perform following operations: Creation of binary tree and traversal recursive
and non-recursive.
3. Implement a dictionary using a binary search tree where the dictionary stores keywords & its meanings.
Perform following operations:
● Insert a keyword
● Delete a keyword
● Create mirror image and display level wise
● Copy
● Create mirror image and display level wise
4. Implement threaded binary tree. Perform inorder traversal on the threaded binary tree.
6. A business house has several offices in different countries; they want to lease phone lines to connect them
with each other and the phone company charges different rent to connect different pairs of cities. (Create &
display of Graph). Solve the problem using Prim’s algorithm.
7. Read the marks obtained by students of second year in an online examination of a particular subject. Find the
maximum and minimum marks obtained in that subject. Use heap data structure and heap sort.
8. Implement direct access file using hashing (linear probing with and without replacement) perform
following operations on it a) Create Database b) Display Database c) Add a record d) Search a record e) Modify
a record
branches
root
leaves
branches
nodes
dge
e
Root: Node without parent (A) Subtree: Tree consisting of a node and its
Siblings: Nodes share the same parent descendants
Ancestors of a node: all the nodes along the path from root to that node A
Descendant of a node: child, grandchild, grand-grandchild, etc.
The height or depth of a tree is defined to be the maximum level of any
node in the tree.(4)
B C D
Degree of a node: the number of subtrees(children) of a node is called degree
Degree of a tree: the maximum of the degree of the nodes in the tree.
Nonterminal nodes: other nodes E F G H
leaf or terminal node: Node that have degree zero (E, I, J, K, G, H, D)
The level of a node is defined by initially letting the root be at level one. If a subtree
node is at level l, then its children are at level l + 1. I J K
A Property Value
Number of nodes 9
B C Height 5
Root Node A
Leaves C,D,F,H,I
D E F
Interior nodes B,E,G
Ancestors of H A,B,E,G
Descendants of B D,E,G,H,I,F
G Siblings of E D,F
Right subtree of A A,C
H I Degree of this tree 3
B c
E F
D
I
G H
B C
F G
D E
H I J K
A A
B C B C
D E F G D E F G
H I H I J K L M N O
A A 1 A
B B 2 B C
C Skewed Binary
Tree 3 D E F G
D
4 H I
E 5
Complete Binary Tree
11/17/2021 Advanced Data Structures 36
Converting tree to binary tree
A A A
B B B
A A A
B C B C B
C
Left child-right sibling
Binary tree
11/17/2021 Advanced Data Structures 38
Representation of Trees
▪ Left Child-Right Sibling Representation
▪ Each node has two links (or pointers).
▪ Each node only has one leftmost child and one closest sibling.
data A
left child right sibling
B C D
E F G I H J
K L M
E C
K F G D
Binary Tree!
L I
M H
J
11/17/2021 Advanced Data Structures 40
Converting to a Binary Tree
A
B
▪Binary tree left child = leftmost child
C
▪Binary tree right child= right sibling
D
A
F E
B C D E
G H
I
F G H
J
I J
Advanced Data Structures
11/17/2021 41
[1] A
Sequential Representation [2] B
[3] C
(1) waste space
[4] D
[1] A (2) insertion/deletion
A [5] E
[2] B problem
[6] F
[3] -- [7]
B G
[4] C [8]
A H
[5] --
[9] I
C [6] --
[7] -- B C
D [8] D
[9] --
D
. . E F G
E
[16] E
H
I
11/17/2021 Advanced Data Structures 42
Node Number Properties
1
2 3
4 5 6 7
8 9 10 11 12 13 14 15
class node{
int data;
node *lchild;
node *rchild;
};
data
left_child right_child
b c
d e
g
f
leftChild
element h
rightChild
11/17/2021 Advanced Data Structures 45
Binary Tree Creation
Algorithm create_r() //Driver for creation
class treenode {
{ Allocate memory for root and accept data;
char data[10]; create_r(root);
treenode *left; }
treenode *right;
friend class tree; int main()
} {
class tree tree bt;
{ bt.create_r();
treenode *root; }
public:
tree(); tree::tree() //constructor
void create_r(); {
void create_r(treenode *); root=NULL;
}
}
11/17/2021 Advanced Data Structures 46
Algorithm create_r(treenode * temp) //workhorse for creation
{
Accept choice whether data is added to left of temp->data;
if ch=‘y’
{
Allocate a memory for curr and accept data;
temp->left=curr;
create_r(curr);
}
• Let L, V/D 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
▪ Breadth First
▪ Depth First
▪ Inorder
▪ Preorder
▪ Postorder
b c
f
d e
g h i j
g d h b e i a f j c
b c
f
d e
g h i j
a b d g h e i c f j
b c
f
d e
g h i j
g h d i e b j f c a
pre-order (red): F, B, A, D, C, E, G, I, H;
in-order (yellow): A, B, C, D, E, F, G, H, I;
post-order (green): A, C, E, D, B, H, I, G, F.
At 13 – do left
11/17/2021 Advanced Data Structures 59
Use of the Activation Stack
With a recursive module, we can make use of 13
the activation stack to visit the sub-trees and
“remember” where we left off.
9 42
At 9 – do left
At 13 – do left
11/17/2021 Advanced Data Structures 60
Use of the Activation Stack
With a recursive module, we can make use of 13
the activation stack to visit the sub-trees and
“remember” where we left off.
9 42
At 2 – do left
At 9 – do left
At 13 – do left
11/17/2021 Advanced Data Structures 61
Use of the Activation Stack
With a recursive module, we can make use of 13
the activation stack to visit the sub-trees and
“remember” where we left off.
9 42
At 2 – print
At 9 – do left
At 13 – do left
11/17/2021 Advanced Data Structures 62
Use of the Activation Stack
With a recursive module, we can make use of 13
the activation stack to visit the sub-trees and
“remember” where we left off.
9 42
At 2 – do right
At 9 – do left
At 13 – do left
11/17/2021 Advanced Data Structures 63
Use of the Activation Stack
With a recursive module, we can make use of 13
the activation stack to visit the sub-trees and
“remember” where we left off.
9 42
At 2 - done
At 9 – do left
At 13 – do left
11/17/2021 Advanced Data Structures 64
Use of the Activation Stack
With a recursive module, we can make use of 13
the activation stack to visit the sub-trees and
“remember” where we left off.
9 42
At 9 – Print
At 13 – do left
11/17/2021 Advanced Data Structures 65
Use of the Activation Stack
With a recursive module, we can make use of 13
the activation stack to visit the sub-trees and
“remember” where we left off.
9 42
At 9 – do right
At 13 – do left
11/17/2021 Advanced Data Structures 66
Use of the Activation Stack
With a recursive module, we can make use of 13
the activation stack to visit the sub-trees and
“remember” where we left off.
9 42
At 9 – done
At 13 – do left
11/17/2021 Advanced Data Structures 67
Use of the Activation Stack
With a recursive module, we can make use of 13
the activation stack to visit the sub-trees and
“remember” where we left off.
9 42
At 13 – print
11/17/2021 Advanced Data Structures 68
Use of the Activation Stack
With a recursive module, we can make use of 13
the activation stack to visit the sub-trees and
“remember” where we left off.
9 42
At 13 – do right
11/17/2021 Advanced Data Structures 69
Use of the Activation Stack
With a recursive module, we can make use of 13
the activation stack to visit the sub-trees and
“remember” where we left off.
9 42
At 42 – do left
At 13 – do right
11/17/2021 Advanced Data Structures 70
Use of the Activation Stack
With a recursive module, we can make use of 13
the activation stack to visit the sub-trees and
“remember” where we left off.
9 42
At 42 – print
At 13 – do right
11/17/2021 Advanced Data Structures 71
Use of the Activation Stack
With a recursive module, we can make use of 13
the activation stack to visit the sub-trees and
“remember” where we left off.
9 42
At 42 – do right
At 13 – do right
11/17/2021 Advanced Data Structures 72
Use of the Activation Stack
At 42 – done
At 13 – do right
11/17/2021 Advanced Data Structures 73
Use of the Activation Stack
With a recursive module, we can make use of 13
the activation stack to visit the sub-trees and
“remember” where we left off.
9 42
At 13 – done
11/17/2021 Advanced Data Structures 74
Preorder Traversal (recursive version)
class stack
{
int top;
treenode *data[30];
public:
stack()
{
top=-1;
}
void push(treenode *temp);
treenode *pop();
int empty();
friend class tree;
};
11/17/2021 Advanced Data Structures 77
Nonrecursive Inorder Traversal
Algorithm inorder() {
temp = root; //start traversing the binary tree at the root node
while(1) {
while(temp is not NULL)
{
push temp onto stack;
temp = temp ->left;
}
if stack empty
break;
pop stack into temp;
visit temp; //visit the node
temp = temp ->right; //move to the right child pre-order (red): F, B, A, D, C, E, G, I, H;
} //end while in-order (yellow): A, B, C, D, E, F, G, H, I;
} //end algorithm post-order (green): A, C, E, D, B, H, I, G, F.
f
Remove from queue into temp; d e
visit temp; Queue
if(temp->left is not NULL) a
insert temp->left into queue;
if(temp->right is not NULL)
insert temp->right into queue; Answer
}
}
f
Remove from queue into temp; d e
visit temp; Queue
if(temp->left is not NULL)
insert temp->left into queue;
if(temp->right is not NULL)
insert temp->right into queue; Answer
a
}
}
f
Remove from queue into temp; d e
visit temp; Queue
if(temp->left is not NULL) b c
insert temp->left into queue;
if(temp->right is not NULL)
insert temp->right into queue; Answer
a
}
}
f
Remove from queue into temp; d e
visit temp; Queue
if(temp->left is not NULL) c
insert temp->left into queue;
if(temp->right is not NULL)
insert temp->right into queue; Answer
ab
}
}
f
Remove from queue into temp; d e
visit temp; Queue
if(temp->left is not NULL) c d e
insert temp->left into queue;
if(temp->right is not NULL)
insert temp->right into queue; Answer
ab
}
}
f
Remove from queue into temp; d e
visit temp; Queue
if(temp->left is not NULL) d e
insert temp->left into queue;
if(temp->right is not NULL)
insert temp->right into queue; Answer
abc
}
}
f
Remove from queue into temp; d e
visit temp; Queue
if(temp->left is not NULL) d e f
insert temp->left into queue;
if(temp->right is not NULL)
insert temp->right into queue; Answer
abc
}
}
f
Remove from queue into temp; d e
visit temp; Queue
if(temp->left is not NULL) e f
insert temp->left into queue;
if(temp->right is not NULL)
insert temp->right into queue; Answer
abcd
}
}
f
Remove from queue into temp; d e
visit temp; Queue
if(temp->left is not NULL) f
insert temp->left into queue;
if(temp->right is not NULL)
insert temp->right into queue; Answer
abcde
}
}
f
Remove from queue into temp; d e
visit temp; Queue
if(temp->left is not NULL)
insert temp->left into queue;
if(temp->right is not NULL)
insert temp->right into queue; Answer
abcdef
}
}
It is a binary tree.It may be empty.If it is not empty then it satisfies the following properties
◦ Binary search trees provide an excellent structure for searching a list and at the same time for
inserting and deleting data into the list.
Delete(17) 10
5 15
2 9 20
7 17 30
It this case, node is cut from the tree and algorithm links single child (with it's subtree) directly to the parent
of the removed node.
5 15
2 9 20
7 30
◦ To the inorder’s successor ,attach the left of the node which we want to delete
2 9 20
7 17 30
7 17 30
11/17/2021 Advanced Data Structures 113
else if(curr!=root) //deletion of node which is not root
{ else if(curr->rightc is NULL) //deletion of a
if(curr left and right is NULL ) //deletion of a leaf single child
{ {
if(parent->leftc==curr) if(parent->leftc==curr)
parent->leftc=NULL; parent->leftc=curr->leftc;
else else
parent->rightc=NULL;
parent->rightc=curr->leftc;
}
} 10
else if(curr->leftc is NULL) //deletion of a single child
{
if(parent->leftc==curr)
5 15
parent->leftc=curr->rightc;
else
parent->rightc=curr->rightc; 2 9 20
}
7 17 30
11/17/2021 Advanced Data Structures 114
else //deletion of a node having two child
{
s=curr->rightc;
temp=curr->leftc;
while(s->leftc!=NULL)
{
s=s->leftc;
}
s->leftc=temp;
if(parent->leftc==curr)
10
parent->leftc=curr->rightc;
else 5 15
parent->rightc=curr->rightc;
}
} 2 9 20
Assign curr left and right to NULL;
delete curr;
} 7 17 30
11/17/2021 Advanced Data Structures 115
Assignment no 2
Implement dictionary using binary search tree where dictionary stores keywords & its meanings.
Perform following operations:
1. Insert a keyword
2. Delete a keyword
3. Create mirror image and display level wise
4. Copy
In a linked representation of a binary tree, the number of null links (null pointers) are
actually more than non-null pointers.
Consider the following binary tree:
▪According to this idea we are going to replace all the null pointers by the
appropriate pointer values called threads.
▪And binary tree with such pointers are called threaded tree.
B C
D E F G
H I
Inorder sequence: H, D, I, B, E, A, F, C, G
If ptr->right_child is null,
replace it with a pointer to the node that would be
visited after ptr in an inorder traversal
dangling D E F G
inorder traversal:
I H, D, I, B, E, A, F, C, G
H
•The original tree becomes the left subtree of the head node.
t A t
t B t t B t
t D t f E f f D f f E f
f H f f I f
tbtnode::tbtnode() tbt::tbt()
{ {
lbit=0;
Allocate memory for head;
rbit=0;
} Set rbit to 1;
Assign head->left and right to head;
}
do curr->rightc=temp;
{ curr->leftc=temp->leftc;
Initialize flag to 0; temp->leftc=curr;
temp=root; temp->lbit=1;
Allocate memory to curr and accept curr->data; flag=1;
}
else
temp=temp->leftc;
}while(ch=='y');
} //end algo
11/17/2021 Advanced Data Structures 130
Algorithm inorder() t - t
{
temp = head;
while(1) t A t
{
temp=inordersucc(temp);
if(temp == head) break; t B t t B t
print temp->data;
} t D t E
f f f D f f E f
}
Algorithm node * inordersucc(temp) f H f f I f
{
x=temp->right;
if(temp->rbit==1)
{
while(x->lbit==1)
x=x->left;
}
return x;
}
11/17/2021 Advanced Data Structures 131
t - t
Algorithm preorder()
{ t A t
Assign temp to head->left;
while(temp != head)
t B t t B t
{
print temp->data;
while(temp->lbit != 0) t D t f E f f D f f E f
{
move temp to temp->left;
f H f f I f
print temp->data;
}
while(temp->rbit == 0)
move temp to temp->right;
move temp to temp->right;
}
◦ We can efficiently determine the predecessor and successor nodes starting from any node. In case of
unthreaded binary tree, however, this task is more time consuming and difficult.
◦ Any node can be accessible from any other node. Threads are usually more to upward whereas links are
downward. Thus in a threaded tree, one can move in their direction and nodes are in fact circularly linked.
This is not possible in unthreaded counter part because there we can move only in downward direction
starting from root.
• Insertion and deletion from a threaded tree are very time consuming operation compare
to non-threaded binary tree.
The operators, constants, and variables are arranged in such a way that an inorder traversal of the
tree produces the original expression without parentheses.
+
3 -
3+4*5-9+6 3+(4*5-(9+6))
* +
4 5 9 6
lo
g
log x log(x)
x
!
n! n!
n
137
A Binary Expression Tree
‘*’
‘+’ ‘3’
‘4’ ‘2’
( 4 + 2 ) * 3 = 18
11/17/2021 Advanced Data Structures 138
Why Expression trees?
Expression trees are used to remove ambiguity in expressions.
Consider the algebraic expression 2 - 3 * 4 + 5.
Without the use of precedence rules or parentheses, different orders of evaluation are possible:
((2-3)*(4+5)) = -9
((2-(3*4))+5) = -5
(2-((3*4)+5)) = -15
(((2-3)*4)+5) = 1
(2-(3*(4+5))) = -25
The expression is ambiguous because it uses infix notation: each operator is placed between its operands.
‘*’
‘-’ ‘/’
‘4’ ‘2’
Infix: ((8-5)*((4+2)/3))
Prefix: *-85 /+423
Postfix: 85- 42+3/*
11/17/2021 Advanced Data Structures 141
Inorder Traversal: (A + H) / (M - Y)
Print second
tree
‘/’
‘+’ ‘-’
‘/’
‘+’ ‘-’
‘/’
‘+’ ‘-’
begin
for i=1 to |E| do
if E[i] is an operand then
create a node for the operand;
add it to the stack
else if E[i] is an operator then
create a node for the operator(root/parent)
end
Convert RPN expression to expression tree
expression stack comments Binary tree
+
8 top Create leaf node 8 and push address
onto stack
+ 1 5 8
-
Create node “-” and pop 1, 4 +
8 top from stack as its children.
+ 1 5 8 4 1
- top
Push node ‘-’ onto stack
8
+
11/17/2021 Advanced Data Structures 147
Convert RPN expression to expression tree contd…
expression stack comments Binary tree
In the diagram above, the lowest common ancestor of the nodes 4 and 6 is the node 3.
Node 3 is the lowest node which has nodes 4 and 6 as descendants.
Input Format
The first line contains n, number of nodes in the tree.
Each of the next n lines contains two integers, a b, where a is the index of left child, and b is
the index of right child of ith node.
Note: -1 is used to represent a null node.
Output Format
Sample Input 0
For each k, perform the swap operation and store the indices of your in-order traversal to your
3 array.
result
2After
3 all swap operations have been performed, return your result array for printing.
-1 -1
-1 -1
2
1
1
Sample Output 0
312
213
11/17/2021 Advanced Data Structures 151