SlideShare une entreprise Scribd logo
1  sur  33
Télécharger pour lire hors ligne
Data Structures
Sanjivani Rural Education Society’s
Sanjivani College of Engineering, Kopargaon-423603
(An Autonomous Institute Affiliated to Savitribai Phule Pune University, Pune)
NAAC ‘A’ Grade Accredited, ISO 9001:2015 Certified
Department of Information Technology
(NBAAccredited)
Ms. K. D. Patil
Assistant Professor
Tree
• General Trees, Tree Terminology, Binary Trees, Use binary trees,
Conversion of general tree to binary tree, Array Based
representation of Binary Tree, Binary tree as an ADT, Binary tree
traversals - recursive and non-recursive algorithms, Construction
of tree from its traversals, Huffman coding algorithm
Data Structures Mrs. Kanchan Patil Department of Information Technology
Binary Tree Traversals
Data Structures Mrs. Kanchan Patil Department of Information Technology
• Binary Tree traversal requires that each node of the tree be processed once and
only once in the pre-determined sequence
• There are two approaches
• Depth First Search (DFS)
• Breadth First Search (BFS)
Depth First Search Traversal
Data Structures Mrs. Kanchan Patil Department of Information Technology
• DFS processing proceeds along a path from the root through one child to the most
distinct descendent of that first child
• Means,
• Process all the descendants of a child before going on to the next child
• Different approaches of DSF
• Pre-order Traversal
• Post-order Traversal
• In-order Traversal
Pre-order Traversal (NLR)
Data Structures Mrs. Kanchan Patil Department of Information Technology
• The root node is processed first, followed by left sub-tree and then the right sub-
tree
• Root goes before the sub-tree
• Given a recursion characteristics of trees, implement the traversals recursively
• First, process the root, then left sub-tree and then right sub-tree
• The left sub-tree in turn processes recursively and then the right sub-tree
Pre-order Traversal (NLR)
Data Structures Mrs. Kanchan Patil Department of Information Technology
• Algorithm: Recursive, implicit stack
class Node
{
int data;
Node left, right;
public Node(int x)
{
data = x;
left = right = null;
}
}
class BT {
Node root; // Root of Binary Tree
BT() { root = null; }
preorder_traversal (Node current_node)
{
if(current_node == null) // if (root ! = NULL)
return;
{
print(current_node.data);
preorder_traversal (current_node.left);
preorder_traversal (current_node.right);
}
}
Example
Data Structures Mrs. Kanchan Patil Department of Information Technology
Quiz..
Data Structures Mrs. Kanchan Patil Department of Information Technology
In-order Traversal (LNR)
Data Structures Mrs. Kanchan Patil Department of Information Technology
• The left sub-tree is processed first, then the root and finally right sub-tree
• Because the left sub-tree is processed first, we trace from the root to left most leaf
node before processing any node
• Start at the root , Visit the left child of each node, then the node, then any
remaining nodes
In-order Traversal (LNR)
Data Structures Mrs. Kanchan Patil Department of Information Technology
• Algorithm: Recursive, implicit stack
class Node
{
int data;
Node left, right;
public Node(int x)
{
data = x;
left = right = null;
}
}
class BT {
Node root; // Root of Binary Tree
BT() { root = null; }
inorder_traversal (Node current_node)
{
if(current_node == null) // if (root ! = NULL)
return;
{
inorder_traversal (current_node.left);
print(current_node.data);
inorder_traversal (current_node.right);
}
}
Example
Data Structures Mrs. Kanchan Patil Department of Information Technology
Quiz..
Data Structures Mrs. Kanchan Patil Department of Information Technology
Post-order Traversal (LRN)
Data Structures Mrs. Kanchan Patil Department of Information Technology
• It processes the root node after the left and right sub-trees have been processed
• It starts by locating the left-most leaf and processing it, then processes its right
siblings including its sub-tree and finally node
Post-order Traversal (LRN)
Data Structures Mrs. Kanchan Patil Department of Information Technology
• Algorithm: Recursive, implicit stack
class Node
{
int data;
Node left, right;
public Node(int x)
{
data = x;
left = right = null;
}
}
class BT {
Node root; // Root of Binary Tree
BT() { root = null; }
postorder_traversal (Node current_node)
{
if(current_node == null) // if (root ! = NULL)
return;
{
postorder_traversal (current_node.left);
postorder_traversal (current_node.right);
print(current_node.data);
}
}
Example
Data Structures Mrs. Kanchan Patil Department of Information Technology
Time Complexity
Data Structures Mrs. Kanchan Patil Department of Information Technology
• Traversal
• O(1) – to visit self
• O(n) – to visit positions
• Insertion – Worst Case: O(N), Best Case: O(logN)
• Deletion - Worst Case: O(N), Best Case: O(logN)
• Search – Worst Case: O(N), Best Case: O(1)
Applications of Tree Traversals
Data Structures Mrs. Kanchan Patil Department of Information Technology
• Table of Contents:
• When using a tree to represent the hierarchical structure of a document, a
preorder traversal of the tree can be used to produce a table of contents for the
document.
• Computing Disk Space:
• The recursive computation of disk space is emblematic of a postorder traversal,
as we cannot effectively compute the total space used by a directory until after
we know the space that is used by its children directories.
Applications of Tree Traversals
Data Structures Mrs. Kanchan Patil Department of Information Technology
• Parenthetic Representations of a Tree:
• It is not possible to reconstruct a general tree, given only the preorder sequence
of elements. Some additional context is necessary for the structure of the tree
to be well defined. The use of indentation or numbered labels provides such
context, with a very human-friendly presentation.
• Using Inorder Traversal for Tree Drawing:
• An inorder traversal can be applied to the problem of computing a graphical
layout of a binary tree
Quiz..
Data Structures Mrs. Kanchan Patil Department of Information Technology
In-order Traversal (NLR) – Non-recursive
Data Structures Mrs. Kanchan Patil Department of Information Technology
1) Create an empty stack S
2) Initialize current node as root
3) Push the current node to S and set current = current->left until current is NULL
4) If current is NULL and stack is not empty then
a) Pop the top item from stack.
b) Print the popped item, set current = popped_item->right
c) Go to step 3.
5) If current is NULL and stack is empty then we are done.
In-order Traversal (LNR) - Non-recursive
Data Structures Mrs. Kanchan Patil Department of Information Technology
• Non-recursive, explicit stack
Public void inorder()
{
if (root == null)
return;
Stack<Node> s = new Stack<Node>();
Node current = root;
while (current != null || s.size() > 0)
{
// Reach the left most Node of the current Node
while (current != null)
{
// Place pointer to a tree node on the stack before
traversing the node's left subtree
s.push(current);
current = current.left;
}
// Current must be NULL at this point
current = s.pop();
System.out.print(current.data + " ");
// we have visited the node and its left subtree.
// Now, it's right subtree's turn
current = current.right;
}
}
Example - Non-recursive
Data Structures Mrs. Kanchan Patil Department of Information Technology
Pre-order Traversal (LNR) - Non-recursive
Data Structures Mrs. Kanchan Patil Department of Information Technology
1) Create an empty stack S
2) Initialize the current node as root.
3) Push the current node to S and set current = current->left print the peek element in the
stack until the current is NULL.
4) If current is NULL and stack is not empty then
a) Pop the top item from stack.
b) set current = popped_item->right.
c) Go to step 3.
5) If the current is NULL and the stack is empty then we are done.
Pre-order Traversal (LNR) - Non-recursive
Data Structures Mrs. Kanchan Patil Department of Information Technology
• Non-recursive, explicit stack
public void preorder()
{
if (root == null)
return;
Stack<Node> s = new Stack<Node>();
Node current = root;
while (current != null || s.size() > 0)
{
// Reach the left most Node of the current Node
while (current != null)
{
// Place pointer to a tree node on the stack before
traversing the node's left subtree
s.push(current);
System.out.print(current.data + " ");
current = current.left;
}
// Current must be NULL at this point
current = s.pop();
// we have visited the node and its left subtree.
// Now, it's right subtree's turn
current = current.right;
}
}
Example - Non-recursive
Data Structures Mrs. Kanchan Patil Department of Information Technology
Post-order Traversal (LRN) - Non-recursive
• Non-recursive, explicit stack (Using 2 stacks)
• Push root into Stack_One.
• while(Stack_One is not empty)
• Pop the node from Stack_One and push it into Stack_Two.
• Push the left and right child nodes of the popped node into Stack_One.
• End Loop
• Pop-out all the nodes from Stack_Two and print it.
Post-order Traversal (LRN) - Non-recursive
• Non-recursive, explicit stack
public void postorder()
{
if(root ==null)
return ;
Stack s1=new Stack(); //creating stack1 Object
Stack s2=new Stack(); //creating stack2 Object
s1.push(root); // inserting root element to stack1
while(!s1.isEmpty())
{
Node p=(Node)s1.pop(); //remove from stack1
s2.push(p); //inserting ptr to stack2
/*inserting left and right child of ptr */
if(p.left!=null)
s1.push(p.left);
if(p.right!=null)
s1.push(p.right);
}
while(!2.isEmpty())
{
Node temp=(Node)s2.pop();
System.out.print(temp.value+" ");
}
}
Example - Non-recursive
Data Structures Mrs. Kanchan Patil Department of Information Technology
Breadth First Search Traversal (BFS)
Data Structures Mrs. Kanchan Patil Department of Information Technology
• We process all of the children of a node before proceeding with next level
• Given node n, we process all nodes at level n before proceeding at level n+1
• To traverse a tree in Breadth First order, we use queue
• It is also called as level-order traversal
• For the implementation, use a Queue data structure to hold the nodes from each
level in order.
• Extract each node from the list, print its values, then add its children to the queue.
Breadth First Search Traversal (BFS)
Data Structures Mrs. Kanchan Patil Department of Information Technology
• Algorithm:
public void traverseLevelOrder()
{
if (root == null)
{
return;
}
Queue<Node> b = new LinkedList<Node>();
b.add(root);
while (!b.isEmpty())
{
Node node = b.remove();
System.out.print(" " + node.value);
if (node.left != null)
{
b.add(node.left);
}
if (node.right != null)
{
b.add(node.right);
}
}
}
Quiz
Data Structures Mrs. Kanchan Patil Department of Information Technology
References
Data Structures Mrs. Kanchan Patil Department of Information Technology
• R. Lafore, “Data structures and Algorithms in Java”, Pearson education, ISBN: 9788
131718124.
• Michael Goodrich, Roberto Tamassia, Michael H. Goldwasser, “Data Structures and
Algorithms in Java”, 6th edition, wiley publication, ISBN: 978-1-118-77133-4
• R. Gilberg, B. Forouzan, “Data Structure: A Pseudo code approach with C++”, Cengage
Learning.
• Thomas H. Cormen, Charles E. Leiserson and Ronald L. Rivest, “Introduction to
Algorithms”, 2nd Edition, The MIT Press, 2001, ISBN 0-262-03293-7.
• Sartaj Sahni, “Data Structures, Algorithms and Applications in C++”, 2 nd Edition,
Universities Press.
• E. Horowitz, S. Sahni, S. Anderson-freed, “Fundamentals of Data Structures in C”, 2 nd
Edition, University Press, ISBN 978-81-7371-605-8.
Data Structures Mrs. Kanchan Patil Department of Information Technology
Thank You!!!
Happy Learning!!!

Contenu connexe

Similaire à Binary Tree Traversal Types and Algorithms

Fundamentalsofdatastructures 110501104205-phpapp02
Fundamentalsofdatastructures 110501104205-phpapp02Fundamentalsofdatastructures 110501104205-phpapp02
Fundamentalsofdatastructures 110501104205-phpapp02Getachew Ganfur
 
Stacks and Queues with Linked List.pdf
Stacks and Queues with Linked List.pdfStacks and Queues with Linked List.pdf
Stacks and Queues with Linked List.pdfGKalyani4
 
Data structures and algorithms
Data structures and algorithmsData structures and algorithms
Data structures and algorithmsJulie Iskander
 
Introduction to data structure by anil dutt
Introduction to data structure by anil duttIntroduction to data structure by anil dutt
Introduction to data structure by anil duttAnil Dutt
 
Biary search Tree.docx
Biary search Tree.docxBiary search Tree.docx
Biary search Tree.docxsowmya koneru
 
Unit 1_Stack and Queue using Linked Organization.pdf
Unit 1_Stack and Queue using Linked Organization.pdfUnit 1_Stack and Queue using Linked Organization.pdf
Unit 1_Stack and Queue using Linked Organization.pdfKanchanPatil34
 
L1 - Recap.pdf
L1 - Recap.pdfL1 - Recap.pdf
L1 - Recap.pdfIfat Nix
 
Binary tree and operations
Binary tree and operations Binary tree and operations
Binary tree and operations varagilavanya
 
Unit 2_2 Binary Tree as ADT_General Tree.pdf
Unit 2_2 Binary Tree as ADT_General Tree.pdfUnit 2_2 Binary Tree as ADT_General Tree.pdf
Unit 2_2 Binary Tree as ADT_General Tree.pdfKanchanPatil34
 
Presentation on Elementary data structures
Presentation on Elementary data structuresPresentation on Elementary data structures
Presentation on Elementary data structuresKuber Chandra
 
Binary Tree - Algorithms
Binary Tree - Algorithms Binary Tree - Algorithms
Binary Tree - Algorithms CourseHunt
 
Binary Search Tree
Binary Search TreeBinary Search Tree
Binary Search Treesagar yadav
 
Implementation of queue using singly and doubly linked list.
Implementation of queue using singly and doubly linked list.Implementation of queue using singly and doubly linked list.
Implementation of queue using singly and doubly linked list.central university of bihar
 
1.introduction to data_structures
1.introduction to data_structures1.introduction to data_structures
1.introduction to data_structurespcnmtutorials
 
Lecture notes data structures tree
Lecture notes data structures   treeLecture notes data structures   tree
Lecture notes data structures treemaamir farooq
 

Similaire à Binary Tree Traversal Types and Algorithms (20)

Fundamentalsofdatastructures 110501104205-phpapp02
Fundamentalsofdatastructures 110501104205-phpapp02Fundamentalsofdatastructures 110501104205-phpapp02
Fundamentalsofdatastructures 110501104205-phpapp02
 
Stacks and Queues with Linked List.pdf
Stacks and Queues with Linked List.pdfStacks and Queues with Linked List.pdf
Stacks and Queues with Linked List.pdf
 
Data structures and algorithms
Data structures and algorithmsData structures and algorithms
Data structures and algorithms
 
Introduction to data structure by anil dutt
Introduction to data structure by anil duttIntroduction to data structure by anil dutt
Introduction to data structure by anil dutt
 
Biary search Tree.docx
Biary search Tree.docxBiary search Tree.docx
Biary search Tree.docx
 
Unit 1_Stack and Queue using Linked Organization.pdf
Unit 1_Stack and Queue using Linked Organization.pdfUnit 1_Stack and Queue using Linked Organization.pdf
Unit 1_Stack and Queue using Linked Organization.pdf
 
L1 - Recap.pdf
L1 - Recap.pdfL1 - Recap.pdf
L1 - Recap.pdf
 
Binary tree and operations
Binary tree and operations Binary tree and operations
Binary tree and operations
 
Unit 2_2 Binary Tree as ADT_General Tree.pdf
Unit 2_2 Binary Tree as ADT_General Tree.pdfUnit 2_2 Binary Tree as ADT_General Tree.pdf
Unit 2_2 Binary Tree as ADT_General Tree.pdf
 
Presentation on Elementary data structures
Presentation on Elementary data structuresPresentation on Elementary data structures
Presentation on Elementary data structures
 
Binary Tree - Algorithms
Binary Tree - Algorithms Binary Tree - Algorithms
Binary Tree - Algorithms
 
Data structure
Data  structureData  structure
Data structure
 
Binary Search Tree
Binary Search TreeBinary Search Tree
Binary Search Tree
 
Data Structure
Data StructureData Structure
Data Structure
 
Implementation of queue using singly and doubly linked list.
Implementation of queue using singly and doubly linked list.Implementation of queue using singly and doubly linked list.
Implementation of queue using singly and doubly linked list.
 
Unit iv data structure-converted
Unit  iv data structure-convertedUnit  iv data structure-converted
Unit iv data structure-converted
 
ELEMENTARY DATASTRUCTURES
ELEMENTARY DATASTRUCTURESELEMENTARY DATASTRUCTURES
ELEMENTARY DATASTRUCTURES
 
Linear data structure concepts
Linear data structure conceptsLinear data structure concepts
Linear data structure concepts
 
1.introduction to data_structures
1.introduction to data_structures1.introduction to data_structures
1.introduction to data_structures
 
Lecture notes data structures tree
Lecture notes data structures   treeLecture notes data structures   tree
Lecture notes data structures tree
 

Plus de KanchanPatil34

PAI Unit 3 Paging in 80386 Microporcessor
PAI Unit 3 Paging in 80386 MicroporcessorPAI Unit 3 Paging in 80386 Microporcessor
PAI Unit 3 Paging in 80386 MicroporcessorKanchanPatil34
 
PAI Unit 3 Multitasking in 80386
PAI Unit 3 Multitasking in 80386PAI Unit 3 Multitasking in 80386
PAI Unit 3 Multitasking in 80386KanchanPatil34
 
PAI Unit 2 Segmentation in 80386 microprocessor
PAI Unit 2 Segmentation in 80386 microprocessorPAI Unit 2 Segmentation in 80386 microprocessor
PAI Unit 2 Segmentation in 80386 microprocessorKanchanPatil34
 
PAI Unit 2 Protection in 80386 segmentation
PAI Unit 2 Protection in 80386 segmentationPAI Unit 2 Protection in 80386 segmentation
PAI Unit 2 Protection in 80386 segmentationKanchanPatil34
 
SE PAI Unit 2_Data Structures in 80386 segmentation
SE PAI Unit 2_Data Structures in 80386 segmentationSE PAI Unit 2_Data Structures in 80386 segmentation
SE PAI Unit 2_Data Structures in 80386 segmentationKanchanPatil34
 
SE PAI Unit 5_Timer Programming in 8051 microcontroller_Part 1
SE PAI Unit 5_Timer Programming in 8051 microcontroller_Part 1SE PAI Unit 5_Timer Programming in 8051 microcontroller_Part 1
SE PAI Unit 5_Timer Programming in 8051 microcontroller_Part 1KanchanPatil34
 
SE PAI Unit 5_Timer Programming in 8051 microcontroller_Part 2
SE PAI Unit 5_Timer Programming in 8051 microcontroller_Part 2SE PAI Unit 5_Timer Programming in 8051 microcontroller_Part 2
SE PAI Unit 5_Timer Programming in 8051 microcontroller_Part 2KanchanPatil34
 
SE PAI Unit 5_Serial Port Programming in 8051 micro controller_Part 3
SE PAI Unit 5_Serial Port Programming in 8051 micro controller_Part 3SE PAI Unit 5_Serial Port Programming in 8051 micro controller_Part 3
SE PAI Unit 5_Serial Port Programming in 8051 micro controller_Part 3KanchanPatil34
 
SE PAI Unit 5_Serial Port Programming in 8051 microcontroller_Part 2
SE PAI Unit 5_Serial Port Programming in 8051 microcontroller_Part 2SE PAI Unit 5_Serial Port Programming in 8051 microcontroller_Part 2
SE PAI Unit 5_Serial Port Programming in 8051 microcontroller_Part 2KanchanPatil34
 
SE PAI Unit 5_Serial Port Programming in 8051 microcontroller_Part 1
SE PAI Unit 5_Serial Port Programming in 8051 microcontroller_Part 1SE PAI Unit 5_Serial Port Programming in 8051 microcontroller_Part 1
SE PAI Unit 5_Serial Port Programming in 8051 microcontroller_Part 1KanchanPatil34
 
SE PAI Unit 5_IO programming in 8051
SE PAI Unit 5_IO programming in 8051SE PAI Unit 5_IO programming in 8051
SE PAI Unit 5_IO programming in 8051KanchanPatil34
 
Unit 5_Interrupt programming in 8051 micro controller - part 2
Unit 5_Interrupt programming in 8051 micro controller - part 2Unit 5_Interrupt programming in 8051 micro controller - part 2
Unit 5_Interrupt programming in 8051 micro controller - part 2KanchanPatil34
 
Unit 5_interrupt programming_Part 1
Unit 5_interrupt programming_Part 1Unit 5_interrupt programming_Part 1
Unit 5_interrupt programming_Part 1KanchanPatil34
 
Unit 3 se pai_ivt and idt
Unit 3 se pai_ivt and idtUnit 3 se pai_ivt and idt
Unit 3 se pai_ivt and idtKanchanPatil34
 
Unit 2 se pai_registers in 80386
Unit 2 se pai_registers in 80386Unit 2 se pai_registers in 80386
Unit 2 se pai_registers in 80386KanchanPatil34
 
Unit i se pai_dos function calls
Unit i se pai_dos function callsUnit i se pai_dos function calls
Unit i se pai_dos function callsKanchanPatil34
 
DELD Unit IV ring and twisted ring counter
DELD Unit IV ring and twisted ring counterDELD Unit IV ring and twisted ring counter
DELD Unit IV ring and twisted ring counterKanchanPatil34
 
DELD Unit IV operation modes of shift register
DELD Unit IV operation modes of shift registerDELD Unit IV operation modes of shift register
DELD Unit IV operation modes of shift registerKanchanPatil34
 

Plus de KanchanPatil34 (20)

PAI Unit 3 Paging in 80386 Microporcessor
PAI Unit 3 Paging in 80386 MicroporcessorPAI Unit 3 Paging in 80386 Microporcessor
PAI Unit 3 Paging in 80386 Microporcessor
 
PAI Unit 3 Multitasking in 80386
PAI Unit 3 Multitasking in 80386PAI Unit 3 Multitasking in 80386
PAI Unit 3 Multitasking in 80386
 
PAI Unit 2 Segmentation in 80386 microprocessor
PAI Unit 2 Segmentation in 80386 microprocessorPAI Unit 2 Segmentation in 80386 microprocessor
PAI Unit 2 Segmentation in 80386 microprocessor
 
PAI Unit 2 Protection in 80386 segmentation
PAI Unit 2 Protection in 80386 segmentationPAI Unit 2 Protection in 80386 segmentation
PAI Unit 2 Protection in 80386 segmentation
 
SE PAI Unit 2_Data Structures in 80386 segmentation
SE PAI Unit 2_Data Structures in 80386 segmentationSE PAI Unit 2_Data Structures in 80386 segmentation
SE PAI Unit 2_Data Structures in 80386 segmentation
 
SE PAI Unit 5_Timer Programming in 8051 microcontroller_Part 1
SE PAI Unit 5_Timer Programming in 8051 microcontroller_Part 1SE PAI Unit 5_Timer Programming in 8051 microcontroller_Part 1
SE PAI Unit 5_Timer Programming in 8051 microcontroller_Part 1
 
SE PAI Unit 5_Timer Programming in 8051 microcontroller_Part 2
SE PAI Unit 5_Timer Programming in 8051 microcontroller_Part 2SE PAI Unit 5_Timer Programming in 8051 microcontroller_Part 2
SE PAI Unit 5_Timer Programming in 8051 microcontroller_Part 2
 
SE PAI Unit 5_Serial Port Programming in 8051 micro controller_Part 3
SE PAI Unit 5_Serial Port Programming in 8051 micro controller_Part 3SE PAI Unit 5_Serial Port Programming in 8051 micro controller_Part 3
SE PAI Unit 5_Serial Port Programming in 8051 micro controller_Part 3
 
SE PAI Unit 5_Serial Port Programming in 8051 microcontroller_Part 2
SE PAI Unit 5_Serial Port Programming in 8051 microcontroller_Part 2SE PAI Unit 5_Serial Port Programming in 8051 microcontroller_Part 2
SE PAI Unit 5_Serial Port Programming in 8051 microcontroller_Part 2
 
SE PAI Unit 5_Serial Port Programming in 8051 microcontroller_Part 1
SE PAI Unit 5_Serial Port Programming in 8051 microcontroller_Part 1SE PAI Unit 5_Serial Port Programming in 8051 microcontroller_Part 1
SE PAI Unit 5_Serial Port Programming in 8051 microcontroller_Part 1
 
SE PAI Unit 5_IO programming in 8051
SE PAI Unit 5_IO programming in 8051SE PAI Unit 5_IO programming in 8051
SE PAI Unit 5_IO programming in 8051
 
Unit 5_Interrupt programming in 8051 micro controller - part 2
Unit 5_Interrupt programming in 8051 micro controller - part 2Unit 5_Interrupt programming in 8051 micro controller - part 2
Unit 5_Interrupt programming in 8051 micro controller - part 2
 
Unit 5_interrupt programming_Part 1
Unit 5_interrupt programming_Part 1Unit 5_interrupt programming_Part 1
Unit 5_interrupt programming_Part 1
 
8051 interfacing
8051 interfacing8051 interfacing
8051 interfacing
 
Unit 3 se pai_ivt and idt
Unit 3 se pai_ivt and idtUnit 3 se pai_ivt and idt
Unit 3 se pai_ivt and idt
 
Unit 2 se pai_registers in 80386
Unit 2 se pai_registers in 80386Unit 2 se pai_registers in 80386
Unit 2 se pai_registers in 80386
 
Unit i se pai_dos function calls
Unit i se pai_dos function callsUnit i se pai_dos function calls
Unit i se pai_dos function calls
 
DELD Unit V cpld_fpga
DELD Unit V cpld_fpgaDELD Unit V cpld_fpga
DELD Unit V cpld_fpga
 
DELD Unit IV ring and twisted ring counter
DELD Unit IV ring and twisted ring counterDELD Unit IV ring and twisted ring counter
DELD Unit IV ring and twisted ring counter
 
DELD Unit IV operation modes of shift register
DELD Unit IV operation modes of shift registerDELD Unit IV operation modes of shift register
DELD Unit IV operation modes of shift register
 

Dernier

Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphThiyagu K
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfJayanti Pande
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3JemimahLaneBuaron
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxpboyjonauth
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformChameera Dedduwage
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13Steve Thomason
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfchloefrazer622
 
Separation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesSeparation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesFatimaKhan178732
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Educationpboyjonauth
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdfSoniaTolstoy
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfsanyamsingh5019
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Celine George
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxiammrhaywood
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdfssuser54595a
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationnomboosow
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)eniolaolutunde
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...Marc Dusseiller Dusjagr
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...EduSkills OECD
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxNirmalaLoungPoorunde1
 

Dernier (20)

Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot Graph
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdf
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptx
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy Reform
 
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptxINDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdf
 
Separation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesSeparation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and Actinides
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Education
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdf
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communication
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptx
 

Binary Tree Traversal Types and Algorithms

  • 1. Data Structures Sanjivani Rural Education Society’s Sanjivani College of Engineering, Kopargaon-423603 (An Autonomous Institute Affiliated to Savitribai Phule Pune University, Pune) NAAC ‘A’ Grade Accredited, ISO 9001:2015 Certified Department of Information Technology (NBAAccredited) Ms. K. D. Patil Assistant Professor
  • 2. Tree • General Trees, Tree Terminology, Binary Trees, Use binary trees, Conversion of general tree to binary tree, Array Based representation of Binary Tree, Binary tree as an ADT, Binary tree traversals - recursive and non-recursive algorithms, Construction of tree from its traversals, Huffman coding algorithm Data Structures Mrs. Kanchan Patil Department of Information Technology
  • 3. Binary Tree Traversals Data Structures Mrs. Kanchan Patil Department of Information Technology • Binary Tree traversal requires that each node of the tree be processed once and only once in the pre-determined sequence • There are two approaches • Depth First Search (DFS) • Breadth First Search (BFS)
  • 4. Depth First Search Traversal Data Structures Mrs. Kanchan Patil Department of Information Technology • DFS processing proceeds along a path from the root through one child to the most distinct descendent of that first child • Means, • Process all the descendants of a child before going on to the next child • Different approaches of DSF • Pre-order Traversal • Post-order Traversal • In-order Traversal
  • 5. Pre-order Traversal (NLR) Data Structures Mrs. Kanchan Patil Department of Information Technology • The root node is processed first, followed by left sub-tree and then the right sub- tree • Root goes before the sub-tree • Given a recursion characteristics of trees, implement the traversals recursively • First, process the root, then left sub-tree and then right sub-tree • The left sub-tree in turn processes recursively and then the right sub-tree
  • 6. Pre-order Traversal (NLR) Data Structures Mrs. Kanchan Patil Department of Information Technology • Algorithm: Recursive, implicit stack class Node { int data; Node left, right; public Node(int x) { data = x; left = right = null; } } class BT { Node root; // Root of Binary Tree BT() { root = null; } preorder_traversal (Node current_node) { if(current_node == null) // if (root ! = NULL) return; { print(current_node.data); preorder_traversal (current_node.left); preorder_traversal (current_node.right); } }
  • 7. Example Data Structures Mrs. Kanchan Patil Department of Information Technology
  • 8. Quiz.. Data Structures Mrs. Kanchan Patil Department of Information Technology
  • 9. In-order Traversal (LNR) Data Structures Mrs. Kanchan Patil Department of Information Technology • The left sub-tree is processed first, then the root and finally right sub-tree • Because the left sub-tree is processed first, we trace from the root to left most leaf node before processing any node • Start at the root , Visit the left child of each node, then the node, then any remaining nodes
  • 10. In-order Traversal (LNR) Data Structures Mrs. Kanchan Patil Department of Information Technology • Algorithm: Recursive, implicit stack class Node { int data; Node left, right; public Node(int x) { data = x; left = right = null; } } class BT { Node root; // Root of Binary Tree BT() { root = null; } inorder_traversal (Node current_node) { if(current_node == null) // if (root ! = NULL) return; { inorder_traversal (current_node.left); print(current_node.data); inorder_traversal (current_node.right); } }
  • 11. Example Data Structures Mrs. Kanchan Patil Department of Information Technology
  • 12. Quiz.. Data Structures Mrs. Kanchan Patil Department of Information Technology
  • 13. Post-order Traversal (LRN) Data Structures Mrs. Kanchan Patil Department of Information Technology • It processes the root node after the left and right sub-trees have been processed • It starts by locating the left-most leaf and processing it, then processes its right siblings including its sub-tree and finally node
  • 14. Post-order Traversal (LRN) Data Structures Mrs. Kanchan Patil Department of Information Technology • Algorithm: Recursive, implicit stack class Node { int data; Node left, right; public Node(int x) { data = x; left = right = null; } } class BT { Node root; // Root of Binary Tree BT() { root = null; } postorder_traversal (Node current_node) { if(current_node == null) // if (root ! = NULL) return; { postorder_traversal (current_node.left); postorder_traversal (current_node.right); print(current_node.data); } }
  • 15. Example Data Structures Mrs. Kanchan Patil Department of Information Technology
  • 16. Time Complexity Data Structures Mrs. Kanchan Patil Department of Information Technology • Traversal • O(1) – to visit self • O(n) – to visit positions • Insertion – Worst Case: O(N), Best Case: O(logN) • Deletion - Worst Case: O(N), Best Case: O(logN) • Search – Worst Case: O(N), Best Case: O(1)
  • 17. Applications of Tree Traversals Data Structures Mrs. Kanchan Patil Department of Information Technology • Table of Contents: • When using a tree to represent the hierarchical structure of a document, a preorder traversal of the tree can be used to produce a table of contents for the document. • Computing Disk Space: • The recursive computation of disk space is emblematic of a postorder traversal, as we cannot effectively compute the total space used by a directory until after we know the space that is used by its children directories.
  • 18. Applications of Tree Traversals Data Structures Mrs. Kanchan Patil Department of Information Technology • Parenthetic Representations of a Tree: • It is not possible to reconstruct a general tree, given only the preorder sequence of elements. Some additional context is necessary for the structure of the tree to be well defined. The use of indentation or numbered labels provides such context, with a very human-friendly presentation. • Using Inorder Traversal for Tree Drawing: • An inorder traversal can be applied to the problem of computing a graphical layout of a binary tree
  • 19. Quiz.. Data Structures Mrs. Kanchan Patil Department of Information Technology
  • 20. In-order Traversal (NLR) – Non-recursive Data Structures Mrs. Kanchan Patil Department of Information Technology 1) Create an empty stack S 2) Initialize current node as root 3) Push the current node to S and set current = current->left until current is NULL 4) If current is NULL and stack is not empty then a) Pop the top item from stack. b) Print the popped item, set current = popped_item->right c) Go to step 3. 5) If current is NULL and stack is empty then we are done.
  • 21. In-order Traversal (LNR) - Non-recursive Data Structures Mrs. Kanchan Patil Department of Information Technology • Non-recursive, explicit stack Public void inorder() { if (root == null) return; Stack<Node> s = new Stack<Node>(); Node current = root; while (current != null || s.size() > 0) { // Reach the left most Node of the current Node while (current != null) { // Place pointer to a tree node on the stack before traversing the node's left subtree s.push(current); current = current.left; } // Current must be NULL at this point current = s.pop(); System.out.print(current.data + " "); // we have visited the node and its left subtree. // Now, it's right subtree's turn current = current.right; } }
  • 22. Example - Non-recursive Data Structures Mrs. Kanchan Patil Department of Information Technology
  • 23. Pre-order Traversal (LNR) - Non-recursive Data Structures Mrs. Kanchan Patil Department of Information Technology 1) Create an empty stack S 2) Initialize the current node as root. 3) Push the current node to S and set current = current->left print the peek element in the stack until the current is NULL. 4) If current is NULL and stack is not empty then a) Pop the top item from stack. b) set current = popped_item->right. c) Go to step 3. 5) If the current is NULL and the stack is empty then we are done.
  • 24. Pre-order Traversal (LNR) - Non-recursive Data Structures Mrs. Kanchan Patil Department of Information Technology • Non-recursive, explicit stack public void preorder() { if (root == null) return; Stack<Node> s = new Stack<Node>(); Node current = root; while (current != null || s.size() > 0) { // Reach the left most Node of the current Node while (current != null) { // Place pointer to a tree node on the stack before traversing the node's left subtree s.push(current); System.out.print(current.data + " "); current = current.left; } // Current must be NULL at this point current = s.pop(); // we have visited the node and its left subtree. // Now, it's right subtree's turn current = current.right; } }
  • 25. Example - Non-recursive Data Structures Mrs. Kanchan Patil Department of Information Technology
  • 26. Post-order Traversal (LRN) - Non-recursive • Non-recursive, explicit stack (Using 2 stacks) • Push root into Stack_One. • while(Stack_One is not empty) • Pop the node from Stack_One and push it into Stack_Two. • Push the left and right child nodes of the popped node into Stack_One. • End Loop • Pop-out all the nodes from Stack_Two and print it.
  • 27. Post-order Traversal (LRN) - Non-recursive • Non-recursive, explicit stack public void postorder() { if(root ==null) return ; Stack s1=new Stack(); //creating stack1 Object Stack s2=new Stack(); //creating stack2 Object s1.push(root); // inserting root element to stack1 while(!s1.isEmpty()) { Node p=(Node)s1.pop(); //remove from stack1 s2.push(p); //inserting ptr to stack2 /*inserting left and right child of ptr */ if(p.left!=null) s1.push(p.left); if(p.right!=null) s1.push(p.right); } while(!2.isEmpty()) { Node temp=(Node)s2.pop(); System.out.print(temp.value+" "); } }
  • 28. Example - Non-recursive Data Structures Mrs. Kanchan Patil Department of Information Technology
  • 29. Breadth First Search Traversal (BFS) Data Structures Mrs. Kanchan Patil Department of Information Technology • We process all of the children of a node before proceeding with next level • Given node n, we process all nodes at level n before proceeding at level n+1 • To traverse a tree in Breadth First order, we use queue • It is also called as level-order traversal • For the implementation, use a Queue data structure to hold the nodes from each level in order. • Extract each node from the list, print its values, then add its children to the queue.
  • 30. Breadth First Search Traversal (BFS) Data Structures Mrs. Kanchan Patil Department of Information Technology • Algorithm: public void traverseLevelOrder() { if (root == null) { return; } Queue<Node> b = new LinkedList<Node>(); b.add(root); while (!b.isEmpty()) { Node node = b.remove(); System.out.print(" " + node.value); if (node.left != null) { b.add(node.left); } if (node.right != null) { b.add(node.right); } } }
  • 31. Quiz Data Structures Mrs. Kanchan Patil Department of Information Technology
  • 32. References Data Structures Mrs. Kanchan Patil Department of Information Technology • R. Lafore, “Data structures and Algorithms in Java”, Pearson education, ISBN: 9788 131718124. • Michael Goodrich, Roberto Tamassia, Michael H. Goldwasser, “Data Structures and Algorithms in Java”, 6th edition, wiley publication, ISBN: 978-1-118-77133-4 • R. Gilberg, B. Forouzan, “Data Structure: A Pseudo code approach with C++”, Cengage Learning. • Thomas H. Cormen, Charles E. Leiserson and Ronald L. Rivest, “Introduction to Algorithms”, 2nd Edition, The MIT Press, 2001, ISBN 0-262-03293-7. • Sartaj Sahni, “Data Structures, Algorithms and Applications in C++”, 2 nd Edition, Universities Press. • E. Horowitz, S. Sahni, S. Anderson-freed, “Fundamentals of Data Structures in C”, 2 nd Edition, University Press, ISBN 978-81-7371-605-8.
  • 33. Data Structures Mrs. Kanchan Patil Department of Information Technology Thank You!!! Happy Learning!!!