The document discusses different tree traversal algorithms including depth-first search (DFS) and breadth-first search (BFS). It describes three DFS traversal methods - preorder, inorder, and postorder - and provides recursive and non-recursive algorithms for implementing each. BFS traversal is also covered, which processes all nodes level-by-level using a queue. Examples and applications of the various tree traversal techniques are presented.
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);
}
}
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);
}
}
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);
}
}
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
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;
}
}
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;
}
}
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+" ");
}
}
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);
}
}
}
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!!!