Depth First Search/Traversal in Binary Tree

Objective: Given a Binary Search Tree, Do the Depth First Search/Traversal .

Appraoch:

  • Approach is quite simple, use Stack.
  • First add the add root to the Stack.
  • Pop out an element from Stack and add its right and left children to stack.
  • Pop out an element and print it and add its children.
  • Repeat the above two steps until the Stack id empty.

Example:

DFS

Complete Code:


Output:

Depth-First-Search : 
 1 2 4 5 3 6 7

3 thoughts on “Depth First Search/Traversal in Binary Tree”

  1. I think, we should check if the root is null or not before adding it to the stack otherwise it will throw nullpointer exception.

    Reply

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.