VOOZH about

URL: https://www.geeksforgeeks.org/dsa/dfs-traversal-of-a-tree-using-recursion/

⇱ DFS traversal of a Tree - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

DFS traversal of a Tree

Last Updated : 30 Oct, 2025

Depth-First Search (DFS) is a method used to explore all the nodes in a tree by going as deep as possible along each branch before moving to the next one. It starts at the root node and visits every node in the tree.

Depth-First Search (DFS) can be classified into three main types based on the order in which the nodes are visited:

  • Pre-order Traversal: Visits the root node first, then recursively explores the left and right subtrees.
  • In-order Traversal: Explores the left subtree first, then visits the root, and finally the right subtree.
  • Post-order Traversal: Explores the left and right subtrees first, then visits the root node.
👁 frame_61

Different DFS Traversals of a Tree

1. Inorder Traversal

  • Traverse the left subtree, i.e., call Inorder(left-subtree)
  • Visit the root
  • Traverse the right subtree, i.e., call Inorder(right-subtree)

Output
4 2 5 1 3 6 

Time Complexity: O(N)
Auxiliary Space: O(log N)

Uses of Inorder Traversal

In the case of binary search trees (BST), Inorder traversal gives nodes in non-decreasing order. To get nodes of BST in non-increasing order, a variation of Inorder traversal where Inorder traversal is reversed can be used.

2. Preorder Traversal

  • Visit the root
  • Traverse the left subtree, i.e., call Preorder(left-subtree)
  • Traverse the right subtree, i.e., call Preorder(right-subtree)

Output
1 2 4 5 3 6 

Time Complexity: O(N)
Auxiliary Space: O(log N)

Uses of Preorder Traversal

Preorder traversal is used to create a copy of the tree. Preorder traversal is also used to get prefix expressions of an expression tree.

3. Postorder Traversal

  • Traverse the left subtree, i.e., call Postorder(left-subtree)
  • Traverse the right subtree, i.e., call Postorder(right-subtree)
  • Visit the root



Output
4 5 2 6 3 1 

Time Complexity: O(N)
Auxiliary Space: O(log N)

Uses of Postorder Traversal:

Postorder traversal is used to delete every node of the tree. Postorder traversal is also useful to get the postfix expression of an expression tree

Related Article : Breadth First Traversal.

Comment