VOOZH about

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

⇱ Preorder Traversal of N-ary Tree Without Recursion - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Preorder Traversal of N-ary Tree Without Recursion

Last Updated : 9 Oct, 2025

Given an n-ary tree containing positive node values. The task is to print the preorder traversal without using recursion.
Note: An n-ary tree is a tree where each node can have zero or more children. Unlike a binary tree, which has at most two children per node (left and right), the n-ary tree allows for multiple branches or children for each node.

Examples:

Input: root

1
/ | \
2 3 4
/ \ |
5 6 7

Output: 1 2 5 6 3 7 4

Input: root

11
/ | \
21 29 90
/ / \ \
18 10 12 77

Output: 11 21 18 29 10 12 90 77

Approach:

The idea is to use a stack to simulate recursion and perform iterative preorder traversal. We start by pushing the root into the stack. Then, in each iteration, we pop the top node, process it by adding its data to the result, and push its children from right to left. This ensures the leftmost child is processed first, mimicking recursive preorder traversal. The process continues until the stack is empty, giving the final traversal order.

Steps to implement the above idea:

  • Define a class to represent each node with its value and children.
  • Initialize a storage mechanism (like a stack) to keep track of nodes during traversal.
  • Start from the root node, process it, and store its value in the result.
  • Iterate through its children in a specific order (right to left) and push them onto the stack.
  • Repeat the process until all nodes are visited, ensuring a preorder sequence.
  • Return or display the final result, which contains the nodes in the desired traversal order.

Below is the implementation of the above approach:


Output
11 21 18 29 10 12 90 77 

Time Complexity: O(n), as each node is processed once
Space Complexity: O(n), as in worst case when all nodes are in stack

Comment