VOOZH about

URL: https://www.geeksforgeeks.org/dsa/preorder-traversal-of-a-n-ary-tree/

⇱ Preorder Traversal of an N-ary Tree - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Preorder Traversal of an N-ary Tree

Last Updated : 11 Jul, 2025

Given an N-ary Tree. The task is to write a program to perform the preorder traversal of the given n-ary tree.

Examples:  

Input: 3-Array Tree 
 1
 / | \
 / | \
 2 3 4
 / \ / | \
 5 6 7 8 9
 / / | \ 
 10 11 12 13

Output: 1 2 5 10 6 11 12 13 3 4 7 8 9

Input: 3-Array Tree
 1
 / | \
 / | \
 2 3 4
 / \ / | \
 5 6 7 8 9

Output: 1 2 5 6 3 4 7 8 9

The preorder Traversal of an N-ary Tree is similar to the preorder traversal of a Binary Search Tree or Binary Tree with the only difference that is, all the child nodes of a parent are traversed from left to right in a sequence.
Iterative Preorder Traversal of Binary Tree.

Cases to handle during traversal: Two Cases have been taken care of in this Iterative Preorder Traversal Algorithm: 

  1. Pop the top node from the stack - Top from the stack and insert it into the visited list of nodes.
  2. Push all of the child nodes of Top into the stack from right to left as the traversal from the stack will be carried out in reverse order. As a result, correct preorder traversal is achieved.

Note: In the below python implementation, a "dequeue" is used to implement the stack instead of a list because of its efficient append and pop operations.

Below is the implementation of the above approach:  


Output
1 2 5 10 6 11 12 13 3 4 7 8 9 

Complexity Analysis:

  • Time Complexity: O(N), Where n is the total number of nodes in the given tree.
  • Auxiliary Space: O(h), Where h is the height of the given tree

Using Recursion:

Approach:

  • Create a vector that is used to store the preorder traversal of the N-ary tree.
  • While visiting the node store the value of the node in the vector created and call the recursive function for its children.

Below is the implementation of the above algorithm:


Output
1 2 5 10 6 11 12 13 3 4 7 8 9 

Complexity Analysis:

Time Complexity: O(N), Where n is the total number of nodes in the given tree.
Auxiliary Space: O(h), Where h is the height of the given tree if you consider the Auxiliary stack space of the recursion.

Comment
Article Tags:
Article Tags: