0% found this document useful (0 votes)
29 views

Unit II - Tree - 1 - Updatedv2

The document provides an overview of the Advanced Data Structures course. It outlines the course objectives, outcomes, assessment scheme, syllabus, list of assignments, and learning resources. The course aims to teach students about non-linear data structures like trees and graphs.

Uploaded by

1032221672
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
29 views

Unit II - Tree - 1 - Updatedv2

The document provides an overview of the Advanced Data Structures course. It outlines the course objectives, outcomes, assessment scheme, syllabus, list of assignments, and learning resources. The course aims to teach students about non-linear data structures like trees and graphs.

Uploaded by

1032221672
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 150

CET2001B Advanced Data Structures

S. Y. B. Tech CSE Semester – IV

SCHOOL OF COMPUTER ENGINEERING AND TECHNOLOGY


CET2001B: Advanced Data Structures
Pre-requisites: Fundamentals of Data Structures
Course Objectives:
1. Knowledge
i. Learn the nonlinear data structure and its fundamental concept.
2. Skills
i. Understand the different nonlinear data structures such as Trees and Graph.
ii. Study the concept of symbol table, heap, search tree and multiway search tree.
iii. Study the different ways of file organization and hashing concepts.
3. Attitude
i. Learn to apply advanced concepts of nonlinear data structure to solve real world problems.
Course Outcomes:
After completion of the course the students will be able to :-
1. To choose appropriate non-linear data structures to solve a given problem.
2. To apply advanced data structures for solving complex problems of various domains.
3. To apply various algorithmic strategies to approach the problem solution.
4. To compare and select different file organization and to apply hashing for implementing direct access organization.

14/01/2023 Advanced Data Structures 2


CET2001B Advanced Data Structures:
Assessment Scheme:
Class Continuous Assessment (CCA) - 30 Marks

Laboratory Continuous Assessment (LCA) - 30 Marks

Term End Examination: 40 Marks

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.

Advanced Data Structures 4


Continued…

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.

11/17/2021 Advanced Data Structures 5


List of Assignments
1. Implement following polynomial Operations using Circular Linked List :
1) Create 2) Display 3) Addition

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.

11/17/2021 Advanced Data Structures 6


List of Assignments contd…
5. Consider a friend’s network on Facebook social web site. Model it as a graph to represent each node as a user
and a link to represent the friend relationship between them using adjacency list representation and perform
DFS traversal. Perform BFS traversal for the above graph.

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

9. Implement a AVL tree.


11/17/2021 Advanced Data Structures 7
Learning Resources
Text Books:
1. Fundamentals of Data Structures, E. Horowitz, S. Sahni, S. A-Freed, Universities Press.
2. Data Structures and Algorithms, A. V. Aho, J. E. Hopperoft, J. D. UIlman, Pearson.
Reference Books:
1. The Art of Computer Programming: Volume 1: Fundamental Algorithms, Donald E. Knuth.
2. Introduction to Algorithms, Thomas, H. Cormen, Charles E. Leiserson, Ronald L. Rivest,
Clifford Stein, The MIT Press.
3. Open Data Structures: An Introduction (Open Paths to Enriched Learning), (Thirty First
Edition), Pat Morin, UBC Press.
Supplementary Readings:
1. Aaron Tanenbaum, “Data Structures using C”, Pearson Education.
2. R. Gilberg, B. Forouzan, "Data Structures: A pseudo code approach with C", Cenage
Learning, ISBN 9788131503140
3. R.G.Dromy, “How to Solve it by Computers”, Prentice Hall.

11/17/2021 Advanced Data Structures 9


Learning Resources contd…
Web Resources:
Web links:
1. https://www.tutorialspoint.com/data_structures_algorithms/
MOOCs:
1. http://nptel.ac.in/courses/106102064/1
2. https://nptel.ac.in/courses/106103069/

11/17/2021 Advanced Data Structures 10


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 inorder Threaded Binary tree.
▪ Case Study- Expression tree.

11/17/2021 Advanced Data Structures 12


Natural environment Tree
leaves

branches
root

11/17/2021 Advanced Data Structures 13


Computer Scientist’s View
root

leaves

branches
nodes

11/17/2021 Advanced Data Structures 14


Tree (example)
node

dge
e

11/17/2021 Advanced Data Structures 15


General tree

A tree is a finite set of one or more nodes such that:

(i)There is a specially designated node called the root;


(ii) The remaining nodes are partitioned into n >=0 disjoint sets T1, ...,Tn
where each of these sets is a tree. T1, ...,Tn are called the subtrees of the root.

11/17/2021 Advanced Data Structures 16


Sample Tree

Figure 8: Sample Tree


11/17/2021 Advanced Data Structures 17
Tree Terminology

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

11/17/2021 Advanced Data Structures 18


Tree Properties

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

11/17/2021 Advanced Data Structures 19


Binary Tree

▪ Every node in a binary tree can have at most two children.

▪ 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.

11/17/2021 Advanced Data Structures 20


Structures that are not Binary tree
binary trees
A

B c

E F
D

I
G H

11/17/2021 Advanced Data Structures 21


Maximum Number of Nodes in BT

● The maximum number of nodes on level i of a binary tree is 2i-1, i>=1.

● The maximum number of nodes in a binary tree of depth k is 2k-1, k>=1.

11/17/2021 Advanced Data Structures 22


Binary Trees
▪ A Full binary tree of depth K is a binary tree of depth having 2k-1 nodes
k>=0

▪ Complete Binary Tree


A binary tree T with n levels is complete if all levels except possibly the
last are completely full, and the last level has all its nodes to the left side.

11/17/2021 Advanced Data Structures 23


Complete Binary Trees - Example
A

B C

F G
D E

H I J K

11/17/2021 Advanced Data Structures 24


A Full Binary Tree - Example

11/17/2021 Advanced Data Structures 25


Complete Binary Trees

The second node of a complete


binary tree is always the left child
of the root...
... and the third node is always the
right child of the root.

11/17/2021 Advanced Data Structures 26


Complete Binary Trees

The next nodes must


always fill the next level
from left to right.

11/17/2021 Advanced Data Structures 27


Complete Binary Trees

The next nodes must


always fill the next
level from left to right.

11/17/2021 Advanced Data Structures 28


Complete Binary Trees

The next nodes must


always fill the next
level from left to right.

11/17/2021 Advanced Data Structures 29


Complete Binary Trees

The next nodes must


always fill the next
level from left to right.

11/17/2021 Advanced Data Structures 30


Complete Binary Trees

The next nodes must


always fill the next
level from left to right.

11/17/2021 Advanced Data Structures 31


Complete Binary Trees

The next nodes must


always fill the next
level from left to right.

11/17/2021 Advanced Data Structures 32


Is This Complete?

11/17/2021 Advanced Data Structures 33


Is This Complete?

11/17/2021 Advanced Data Structures 34


Full BT VS Complete BT

A A

B C B C

D E F G D E F G

H I H I J K L M N O

Complete binary tree Full binary tree of depth 4

11/17/2021 Advanced Data Structures 35


Samples of Trees

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

▪ Any tree can be transformed into binary tree.


▪ by left child-right sibling representation

▪ The left subtree and the right subtree are distinguished.

11/17/2021 Advanced Data Structures 37


Tree Representations

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

11/17/2021 Advanced Data Structures 39


Degree Two Tree Representation

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

Parent of node i is node i/2


▪ But node 1 is the root and has no parent
Left child of node i is node 2i if 2i is <=n
▪ But if 2i > n, node i has no left child
Right child of node i is node 2i+1 if 2i+1 is <=n
▪ But if 2i+1 > n, node i has no right child

11/17/2021 Advanced Data Structures 43


Linked Representation

class node{
int data;
node *lchild;
node *rchild;
};
data

left_child data right_child

left_child right_child

11/17/2021 Advanced Data Structures 44


Linked Representation Example
root a

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);
}

Accept choice whether data is added to right of temp->data;


if ch=‘y’
{
Allocate a memory for curr and accept data;
temp->right=curr;
create_r(curr);
}
}

11/17/2021 Advanced Data Structures 47


Algorithm create_nr() temp=temp->left;
{ }
if root=NULL else {
{ if ch='r’
Allocate memory for root and accept the data; } {
do if temp->right=NULL
{
{
temp=root;
temp->right=curr;
flag=0;
allocate memory for curr and accept data; flag=1;
while(flag==0) }
{ temp=temp->right;
Accept choice to add node(left or right); }
if ch='l’ } //else end
{ }//while flag
if temp->left=NULL Accept choice for continuation;
{ temp->left=curr; } // do while end
flag=1; }// algo end
}
11/17/2021 Advanced Data Structures 48
Binary Tree Traversals

• 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

11/17/2021 Advanced Data Structures 49


Binary Tree Traversals
▪A traversal is where each node in a tree is visited once

▪There are two very common traversals

▪ Breadth First
▪ Depth First

11/17/2021 Advanced Data Structures 50


Breadth First
▪In a breadth first traversal all of the nodes on a given level are visited and then all
of the nodes on the next level are visited.

▪Usually in a left to right fashion

▪This is implemented with a queue

11/17/2021 Advanced Data Structures 51


Depth First
▪In a depth first traversal all the nodes on a branch are visited before any others
are visited

▪There are three common depth first traversals

▪ Inorder
▪ Preorder
▪ Postorder

▪Each type has its use and specific application

11/17/2021 Advanced Data Structures 52


Inorder Example (Visit = print)
a

b c
f
d e
g h i j

g d h b e i a f j c

11/17/2021 Advanced Data Structures 53


Preorder Example (Visit = print)
a

b c
f
d e
g h i j

a b d g h e i c f j

11/17/2021 Advanced Data Structures 54


Postorder Example (Visit = print)
a

b c
f
d e
g h i j

g h d i e b j f c a

11/17/2021 Advanced Data Structures 55


Depth first traversal

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.

11/17/2021 Advanced Data Structures 56


Inorder Traversal (recursive version)

Algorithm inorder_r() //Driver


{
inorder_r(root);
}
Algorithm inorder_r(treenode *temp) // Workhorse
{
if temp!=NULL
{
inorder_r(temp->left);
Print temp->data; pre-order (red): F, B, A, D, C, E, G, I, H;
inorder_r(temp->right); in-order (yellow): A, B, C, D, E, F, G, H, I;
post-order (green): A, C, E, D, B, H, I, G, F.
}
}
2/18/2020 DATA STRUCTURES-II 57
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

11/17/2021 Advanced Data Structures 58


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 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

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 – 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)

Algorithm preorder(treenode * temp)


/* preorder tree traversal */
{
if (temp!=NULL) {
print(temp->data);
preorder(temp->left);
predorder(temp->right);
} 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.

2/18/2020 DATA STRUCTURES-II 75


Postorder Traversal (recursive version)

Algorithm postorder(treenode * temp)


/* postorder tree traversal */
{
if (temp!=NULL) {
postorder(temp->left);
postdorder(temp->right);
print(temp->data);
} 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.

2/18/2020 DATA STRUCTURES-II 76


Stack for tree traversal

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.

2/18/2020 DATA STRUCTURES-II 78


Nonrecursive Preorder Traversal
Algorithm preorder() {
temp = root; //start the traversal at the root node
while(1) {
while(temp is not NULL)
{
visit temp;
push temp onto stack;
temp = temp ->left;
}
if stack empty
break;
pop stack into temp;
temp = temp ->right; //visit the right subtree 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.

2/18/2020 DATA STRUCTURES-II 79


Nonrecursive Postorder Traversal
while(stack not empty && stack top right is temp)
{
pop stack into temp;
Algorithm postorder_nr() visit temp
{ }
temp=root; if stack empty
while(1) break;
{ initialise temp to stack top right;
while(temp is not NULL) } // end while
{
push temp onto stack; } // end algorithm
temp = temp ->left;
}
if stack top right is NULL temp=st.data[st.top]->right
{
pre-order (red): F, B, A, D, C, E, G, I, H;
pop stack into temp;
in-order (yellow): A, B, C, D, E, F, G, H, I;
visit temp;
post-order (green): A, C, E, D, B, H, I, G, F.
}

2/18/2020 DATA STRUCTURES-II 80


Algorithm BFS()
{
a
temp=root;
Insert temp into queue;
while Queue not empty
b c
{

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

}
}

11/17/2021 Advanced Data Structures 81


Algorithm BFS()
{
a
temp=root;
Insert temp into queue;
while Queue not empty
b c
{

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
}
}

11/17/2021 Advanced Data Structures 82


Algorithm BFS()
{
a
temp=root;
Insert temp into queue;
while Queue not empty
b c
{

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
}
}

11/17/2021 Advanced Data Structures 83


Algorithm BFS()
{
a
temp=root;
Insert temp into queue;
while Queue not empty
b c
{

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
}
}

11/17/2021 Advanced Data Structures 84


Algorithm BFS()
{
a
temp=root;
Insert temp into queue;
while Queue not empty
b c
{

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
}
}

11/17/2021 Advanced Data Structures 85


Algorithm BFS()
{
a
temp=root;
Insert temp into queue;
while Queue not empty
b c
{

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
}
}

11/17/2021 Advanced Data Structures 86


Algorithm BFS()
{
a
temp=root;
Insert temp into queue;
while Queue not empty
b c
{

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
}
}

11/17/2021 Advanced Data Structures 87


Algorithm BFS()
{
a
temp=root;
Insert temp into queue;
while Queue not empty
b c
{

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
}
}

11/17/2021 Advanced Data Structures 88


Algorithm BFS()
{
a
temp=root;
Insert temp into queue;
while Queue not empty
b c
{

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
}
}

11/17/2021 Advanced Data Structures 89


Algorithm BFS()
{
a
temp=root;
Insert temp into queue;
while Queue not empty
b c
{

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
}
}

11/17/2021 Advanced Data Structures 90


Assignment no 1
2. Implement binary tree and perform following operations: Creation of
binary tree and traversal recursive and non-recursive.

11/17/2021 Advanced Data Structures 91


Operations on binary tree
Copying Binary Tree (recursive)
Copy of binary tree using non recursive is done through preorder
treenode *copy(root)
{
temp=NULL
if (root!=NULL) {

Allocate memory for temp


temp->data=root->data;
temp->left=copy(root->left);
temp->right=copy(root->right);
}
return temp;
}

11/17/2021 Advanced Data Structures 92


Algorithm copy_nr(tree t2)
{ //t2 is original tree s1.push(temp1);
Allocate memory for root s2.push(temp2);
temp1=root;
Move temp1 to temp1->left
temp2=t2.root;
copy(temp1->data,temp2->data); Move temp2 to temp2->left
while(1) }
{ if stack empty break;
while(temp2!=NULL) else
{
{
if(temp2->left!=NULL)
{ Pop to temp1
Allocate memory for temp1->left; Pop to temp2
copy (temp1->left->data,temp2->left->data); temp1=temp1->right;
} temp2=temp2->right;
if(temp2->right!=NULL)
}
{
Allocate memory for temp1->right;; } //end while
copy temp1->right->data,temp2->right->data); }
}

11/17/2021 Advanced Data Structures 93


Erasing nodes in binary tree
Use postorder

11/17/2021 Advanced Data Structures 94


Algorithm depth_r()
Algorithm depth_nr()
{
{
Initialize d to 0;
temp=root; d=depth_r(root);
while(1) print d;
{ }
while(temp!=NULL) Algorithm depth_r(treenode *root)
{
{
push temp;
Initialize t1=0,t2=0;
move temp to temp->left;
if(d<st.top) if(root==NULL)
d=st.top; } return 0;
if(stack top right is NULL) else
{ {
pop to temp; } t1=depth_r(root->left);
while(stack not empty && stack top right is temp)
t2=depth_r(root->right);
{
pop to temp ; }
if(t1>t2)
if stack empty return ++t1;
break; else
move temp to stack top right; return ++t2;
} }
cout<<"\nDepth is "<<d+1; } }
11/17/2021 Advanced Data Structures 95
Algorithm mirror_r() Algorithm mirror_nr()
{ {
mirror_r(root); temp=root;
dispbfs();
q.insqueue(temp);
}
while(!q.empty())
Algorithm mirror_r(treenode *root) {
{ temp=q.delqueue();
swap left and right; swap left and right;
if(root->left!=NULL)
if(temp->left!=NULL)
mirror_r(root->left);
if(root->right!=NULL) q.insqueue(temp->left);
mirror_r(root->right); if(temp->right!=NULL)
} q.insqueue(temp->right);
}
dispbfs();
}

11/17/2021 Advanced Data Structures 96


Binary search Trees

It is a binary tree.It may be empty.If it is not empty then it satisfies the following properties

Every element has a unique key.


The keys in a nonempty left subtree are smaller than the key in the root of subtree.
The keys in a nonempty right subtree are larger than the key in the root of subtree.
The left and right subtrees are also binary search trees.

◦ Binary search trees provide an excellent structure for searching a list and at the same time for
inserting and deleting data into the list.

11/17/2021 Advanced Data Structures 97


Binary Search Tree

All < K All > K

11/17/2021 Advanced Data Structures 98


(a), (b) - complete and balanced trees;
(d) – nearly complete and balanced tree;
(c), (e) – neither complete nor balanced trees

11/17/2021 Advanced Data Structures 99


11/17/2021 Advanced Data Structures 100
Algorithm create()
{ else {
allocate memory and accept the data for root node; if(temp->right=NULL)
do {
{ temp->right=curr;
temp=root;
flag=1;
flag=0;
}
allocate memory and accept the data for curr node;
while(flag==0) else
{ move temp to temp->right;
if(curr->data < temp->data) } //end else
{ } //end while flag
if(temp->left=NULL) Accept choice for adding more nodes;
{
}while(choice =yes); //end do
temp->left=curr;
} //end algorithm
flag=1;
}
else
move temp to temp->left
} //end if compare

11/17/2021 Advanced Data Structures 101


binary search tree creation
Jyoti,Deepa,Rekha,Amit,Gilda,Anita,Abolee,Kaustubh,Teena,Kasturi,Saurabh

11/17/2021 Advanced Data Structures 102


Algorithm search_r(temp, string)
Algorithm search () {
{ Initialize f to 0;
Initialize flag=0; if(temp!=NULL)
Accept string to be searched ; {
flag=search_r(root,str); if(string =temp->data)
if(flag=1) return 1;

print found; if(string< temp->data)


f=search_r(temp->left, str);
else
if(string >temp->data)
print not found;
f=search_r(temp->right, str);
}
}
return f;
}

11/17/2021 Advanced Data Structures 103


Algorithm search_nr()
{
Initialize flag to 0;
temp=root;
Accept string to be searched;
while(flag=0 && temp!=NULL)
{
if(string=temp->data)
{
flag=1; break;
}
else if(string<temp->data)
move temp to temp->left;
else
move temp to temp->right;
} //end while
if(flag=1)
Print found;
else
Print not found;
} //end algo

11/17/2021 Advanced Data Structures 104


Function DeleteItem
First, find the item; then, delete it

Important: binary search tree property must be preserved!!

We need to consider following different cases:


(1) Deleting a leaf
(2) Deleting a node with only one child
(3) Deleting a node with two children
(4) Deleting the root node

11/17/2021 Advanced Data Structures 105


(1) Deleting a leaf

11/17/2021 Advanced Data Structures 106


Deletion - Leaf Case
Algorithm sets corresponding link of the parent to NULL and disposes the node

Delete(17) 10

5 15

2 9 20

7 17 30

11/17/2021 Advanced Data Structures 107


(2) Deleting a node with only one child

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.

11/17/2021 Advanced Data Structures 108


Deletion - One Child Case
Delete(15) 10

5 15

2 9 20

7 30

11/17/2021 Advanced Data Structures 109


(3) Deleting a node with two
children (contd…)

Find inorder successor


◦ Go to the right child and then move to the left till we get NULL for the leftmost node

◦ To the inorder’s successor ,attach the left of the node which we want to delete

11/17/2021 Advanced Data Structures 110


if(curr==root) //deletion of root
{
if(curr->rightc==NULL)
root=root->leftc;
else if(curr->leftc==NULL)
root=root->rightc;
else if(curr->rightc!=NULL && curr->leftc!=NULL) 10
{
temp=curr->leftc;
root=curr->rightc; 5 15
s=curr->rightc;
while(s->leftc!=NULL)
{ 2 9 20
s=s->leftc;
}
s->leftc=temp;
7 17 30
}
}

11/17/2021 Advanced Data Structures 111


else if(curr!=root) //deletion of node which is not root
{
if(curr left and right is NULL ) //deletion of a leaf
{
if(parent->leftc==curr) 10
parent->leftc=NULL;
else
parent->rightc=NULL; 5 15
}

2 9 20

7 17 30

11/17/2021 Advanced Data Structures 112


else if(curr!=root) //deletion of node which is not root
{
if(curr left and right is NULL ) //deletion of a leaf
{
if(parent->leftc==curr)
parent->leftc=NULL;
else
parent->rightc=NULL;
}
else if(curr->leftc is NULL) //deletion of a single child 10
{
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 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

11/17/2021 Advanced Data Structures 116


Threaded Binary Tree

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:

11/17/2021 Advanced Data Structures 117


Threaded Binary Trees

Two many null pointers in current representation of binary trees


n: number of nodes 6
number of non-null links: n-1 5
total links: 2n 12
null links: 2n-(n-1)=n+1 7

Replace these null pointers with some useful “threads”.

11/17/2021 Advanced Data Structures 118


Threaded Binary Tree

The objective here to make effective use of these null pointers.

▪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.

▪In the memory representation of a threaded binary tree, it is necessary to


distinguish between a normal pointer and a thread.

11/17/2021 Advanced Data Structures 119


Threaded Binary Tree
Threading Rules

◦ RightChild null link at node p is replaced by the inorder successor of p.

◦ LeftChild null link at node p is replaced by the inorder predecessor of p.

11/17/2021 Advanced Data Structures 120


Threaded Tree

B C

D E F G

H I

Inorder sequence: H, D, I, B, E, A, F, C, G

11/17/2021 Advanced Data Structures 121


Threads
To distinguish between normal pointers and threads, two Boolean fields,
LeftThread and RightThread, are added to the record in memory representation.

11/17/2021 Advanced Data Structures 122


Threaded Binary Tree
▪Therefore we have an alternate node representation for a threaded binary tree
which contains five fields as show bellow:

11/17/2021 Advanced Data Structures 123


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

11/17/2021 Advanced Data Structures 124


A Threaded Binary Tree
root A
dangling
B C

dangling D E F G

inorder traversal:
I H, D, I, B, E, A, F, C, G
H

11/17/2021 Advanced Data Structures 125


Threads (Contd...)
•To avoid dangling threads, a head node is used in representing a binary tree.

•The original tree becomes the left subtree of the head node.

11/17/2021 Advanced Data Structures 126


Memory Representation of Threaded Tree
t - t

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

11/17/2021 Advanced Data Structures 127


class tbt
{
class tbtnode
tbtnode *head;
{
char data; public:
bool rbit; void create();
bool lbit; void preorder();
tbtnode *rightc; tbtnode* presuccr(tbtnode *temp);
tbtnode *leftc; void inorder();
friend class tbt;
tbtnode* insuccr(tbtnode *temp);
public:
tbtnode(); tbt();
}; };

tbtnode::tbtnode() tbt::tbt()
{ {
lbit=0;
Allocate memory for head;
rbit=0;
} Set rbit to 1;
Assign head->left and right to head;
}

11/17/2021 Advanced Data Structures 128


Algorithm create() while(flag==0)
{ {
Allocate memory for root; Accept choice left or right;
Accept root data; if ch1='l’
Assign head lbit to 1; {
Assign root->leftc and rightc to head; if(temp->lbit==0)
Assign head->leftc to root; {

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;

11/17/2021 Advanced Data Structures }// end if for left 129


t - t
if(ch1=='r')
{
if(temp->rbit==0) t A t
{
curr->leftc=temp; t B t t B t
curr->rightc=temp->rightc;
temp->rightc=curr;
temp->rbit=1; t D t f E f f D f f E f
flag=1;
} f H f f I f
else
temp=temp->rightc;
} // end if for right
} //end while flag
Accept choice for continue;

}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;
}

11/17/2021 Advanced Data Structures 132


Advantages of threaded binary tree:
◦ The traversal operation is more faster than that of its unthreaded version, because with threaded binary tree
non-recursive implementation is possible which can run faster and does not require the botheration of stack
management.

◦ 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.

11/17/2021 Advanced Data Structures 133


Threaded Binary Tree
Disadvantages of threaded binary tree:

• Insertion and deletion from a threaded tree are very time consuming operation compare
to non-threaded binary tree.

• This tree require additional bit to identify the threaded link.

11/17/2021 Advanced Data Structures 134


What is an Expression tree?
An expression tree for an arithmetic, relational, or logical expression is a binary tree in which:

• The parentheses in the expression do not appear.


• The leaves are the variables or constants in the expression.
• The non-leaf nodes are the operators in the expression:

◦ A node for a binary operator has two non-empty subtrees.


◦ A node for a unary operator has one non-empty subtree.

The operators, constants, and variables are arranged in such a way that an inorder traversal of the
tree produces the original expression without parentheses.

11/17/2021 Advanced Data Structures 135


Expression Tree Examples
Inorder Traversal Result Expression Tree Expression
+
a+3 (a+3)
a 3

+
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

11/17/2021 Advanced Data Structures 136


3+4*5-9+6
*
+ -
3 4 5 +
9 6

137
A Binary Expression Tree

‘*’

‘+’ ‘3’

‘4’ ‘2’

What value does it have?

( 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.

11/17/2021 Advanced Data Structures 139


Why Expression trees? (contd...)
•Storing a fully parenthesized expression, such as ((x+2)-(y*(4-z))), is wasteful, since the parentheses in the
expression need to be stored to properly evaluate the expression.
•A compiler will read an expression in a language like Java, and transform it into an expression tree.
•Expression trees impose a hierarchy on the operations in the expression. Terms deeper in the tree get
evaluated first. This allows the establishment of the correct precedence of operations without using
parentheses.
•Expression trees can be very useful for:
• Evaluation of the expression.
• Generating correct compiler code to actually compute the expression's value at execution time.
• Performing symbolic mathematical operations (such as differentiation) on the expression.

11/17/2021 Advanced Data Structures 140


Easy to generate the infix, prefix, postfix expressions
(how?)

‘*’

‘-’ ‘/’

‘8’ ‘5’ ‘+’ ‘3’

‘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

‘/’

‘+’ ‘-’

‘A’ ‘H’ ‘M’ ‘Y’

Print left subtree first Print right subtree last


11/17/2021 Advanced Data Structures 142
Preorder Traversal: / + A H - M Y
Print first
tree

‘/’

‘+’ ‘-’

‘A’ ‘H’ ‘M’ ‘Y’

Print left subtree second Print right subtree last


11/17/2021 Advanced Data Structures 143
Postorder Traversal: A H + M Y - /
Print last
tree

‘/’

‘+’ ‘-’

‘A’ ‘H’ ‘M’ ‘Y’

Print left subtree first Print right subtree second


11/17/2021 Advanced Data Structures 144
Building an Expression Tree
Procedure ExpressionTree(E)

//E is an expression in postfix notation.

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)

pop from the stack ;


make the operand the right subtree of the operator node

pop from the stack;


make the operand the left subtree of the operator node
add it to the stack
11/17/2021
end-for Advanced Data Structures 145

end
Convert RPN expression to expression tree
expression stack comments Binary tree

top Create leaf node 1 and push address 1


1 onto stack

5 top Create leaf node 5 and push address


1 5
onto stack
1

Create node “+” and pop 5, 1 from stack as its


+
children.
top
1 5

+ top Push address of node “+” to stack

+
8 top Create leaf node 8 and push address
onto stack
+ 1 5 8

11/17/2021 Advanced Data Structures 146


Convert RPN expression to expression tree contd…
expression stack comments Binary tree

4 top Create leaf node 4 and push address +


onto stack
8
1 5 8 4
+

1 top Create leaf node 1 and push address +


onto stack
4
1 5 8 4 1
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

Create node “-” and pop “-”, 8 from


+ top stack as its children. -
+ -

- top Push node “-” onto stack 1 5 8


+ 4 1

Create node “*” and pop “-”, “+” *


from stack as its children. -
top
+ -
* top Push node “*” onto stack
1 5 8
4 1

Only one address on the stack, this address is root of


the tree
11/17/2021 Advanced Data Structures 148
Practice Problems
1.Given a pointer to the root of a binary tree, print the top view of the binary
tree.
The tree as seen from the top the nodes, is called the top view of the tree.
For example :
Sample Input: Sample Output- 1->2->5->6

11/17/2021 Advanced Data Structures 149


2. You are given pointer to the root of the binary search tree and two values v1 and v2 .
You need to return the lowest common ancestor (LCA) of v1 and v2 in the binary search
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.

11/17/2021 Advanced Data Structures 150


3. Given a tree and an integer, k, in one operation, we need to swap the subtrees of all the nodes at each
depth h, where h ∈ [k, 2k, 3k,...]. In other words, if h is a multiple of k, swap the left and right subtrees of
that level.
You are given a tree of n nodes where nodes are indexed from [1..n] and it is rooted at 1. You have to
perform t swap operations on it, and after each swap operation print the in-order traversal of the
current state of the tree.

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

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy