Preorder Traversal of Nary Tree Without Recursion (original) (raw)
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:
C++ `
// C++ Code to perform the preorder traversal // of an N-ary tree without using recursion #include <bits/stdc++.h> using namespace std;
class Node { public: int data; vector<Node*> children;
Node(int x) {
data = x;
}};
// Function to perform iterative preorder traversal vector nAryPreorderTraversal(Node* root) {
// Vector to store the traversal result
vector<int> result;
// If the tree is empty, return empty result
if (!root) {
return result;
}
stack<Node*> stk;
stk.push(root);
while (!stk.empty()) {
Node* curr = stk.top();
stk.pop();
result.push_back(curr->data);
// Push children from right to left
for (int i = curr->children.size() - 1; i >= 0; i--) {
stk.push(curr->children[i]);
}
}
return result;}
// Function to print the result vector void printArr(vector& arr) { for (int x : arr) { cout << x << " "; } }
int main() {
// Representation of given N-ary tree
// 11
// / | \
// 21 29 90
// / / \ \
// 18 10 12 77
Node* root = new Node(11);
root->children.push_back(new Node(21));
root->children.push_back(new Node(29));
root->children.push_back(new Node(90));
root->children[0]->children.push_back(new Node(18));
root->children[1]->children.push_back(new Node(10));
root->children[1]->children.push_back(new Node(12));
root->children[2]->children.push_back(new Node(77));
vector<int> result = nAryPreorderTraversal(root);
printArr(result);
return 0;}
Java
// Java Code to perform the preorder traversal // of an N-ary tree without using recursion import java.util.*;
class Node { int data; List children;
Node(int x) {
data = x;
children = new ArrayList<>();
}}
class GfG {
// Function to perform iterative preorder traversal
static List<Integer> nAryPreorderTraversal(Node root) {
// List to store the traversal result
List<Integer> result = new ArrayList<>();
// If the tree is empty, return empty result
if (root == null) {
return result;
}
Stack<Node> stk = new Stack<>();
stk.push(root);
while (!stk.isEmpty()) {
Node curr = stk.pop();
result.add(curr.data);
// Push children from right to left
for (int i = curr.children.size() - 1; i >= 0; i--) {
stk.push(curr.children.get(i));
}
}
return result;
}
// Function to print the result list
static void printArr(List<Integer> arr) {
for (int x : arr) {
System.out.print(x + " ");
}
}
public static void main(String[] args) {
// Representation of given N-ary tree
// 11
// / | \
// 21 29 90
// / / \ \
// 18 10 12 77
Node root = new Node(11);
root.children.add(new Node(21));
root.children.add(new Node(29));
root.children.add(new Node(90));
root.children.get(0).children.add(new Node(18));
root.children.get(1).children.add(new Node(10));
root.children.get(1).children.add(new Node(12));
root.children.get(2).children.add(new Node(77));
List<Integer> result = nAryPreorderTraversal(root);
printArr(result);
}}
Python
Python Code to perform the preorder traversal
of an N-ary tree without using recursion
class Node: def init(self, x): self.data = x self.children = []
Function to perform iterative preorder traversal
def nAryPreorderTraversal(root):
# List to store the traversal result
result = []
# If the tree is empty, return empty result
if not root:
return result
stk = [root]
while stk:
curr = stk.pop()
result.append(curr.data)
# Push children from right to left
for i in range(len(curr.children) - 1, -1, -1):
stk.append(curr.children[i])
return resultFunction to print the result list
def printArr(arr): print(" ".join(map(str, arr)))
if name == "main":
# Representation of given N-ary tree
# 11
# / | \
# 21 29 90
# / / \ \
# 18 10 12 77
root = Node(11)
root.children.append(Node(21))
root.children.append(Node(29))
root.children.append(Node(90))
root.children[0].children.append(Node(18))
root.children[1].children.append(Node(10))
root.children[1].children.append(Node(12))
root.children[2].children.append(Node(77))
result = nAryPreorderTraversal(root)
printArr(result)C#
// C# Code to perform the preorder traversal // of an N-ary tree without using recursion using System; using System.Collections.Generic;
class Node { public int data; public List children;
public Node(int x) {
data = x;
children = new List<Node>();
}}
class GfG {
// Function to perform iterative preorder traversal
static List<int> nAryPreorderTraversal(Node root) {
// List to store the traversal result
List<int> result = new List<int>();
// If the tree is empty, return empty result
if (root == null) {
return result;
}
Stack<Node> stk = new Stack<Node>();
stk.Push(root);
while (stk.Count > 0) {
Node curr = stk.Pop();
result.Add(curr.data);
// Push children from right to left
for (int i = curr.children.Count - 1; i >= 0; i--) {
stk.Push(curr.children[i]);
}
}
return result;
}
// Function to print the result list
static void printArr(List<int> arr) {
foreach (int x in arr) {
Console.Write(x + " ");
}
}
public static void Main() {
// Representation of given N-ary tree
// 11
// / | \
// 21 29 90
// / / \ \
// 18 10 12 77
Node root = new Node(11);
root.children.Add(new Node(21));
root.children.Add(new Node(29));
root.children.Add(new Node(90));
root.children[0].children.Add(new Node(18));
root.children[1].children.Add(new Node(10));
root.children[1].children.Add(new Node(12));
root.children[2].children.Add(new Node(77));
List<int> result = nAryPreorderTraversal(root);
printArr(result);
}}
JavaScript
// Node class representing each node of the N-ary tree class Node { constructor(x) { this.data = x; this.children = []; } }
// Function to perform iterative preorder traversal function nAryPreorderTraversal(root) {
// List to store the traversal result
let result = [];
// If the tree is empty, return empty result
if (!root) {
return result;
}
let stk = [root];
while (stk.length) {
let curr = stk.pop();
result.push(curr.data);
// Push children from right to left
for (let i = curr.children.length - 1; i >= 0; i--) {
stk.push(curr.children[i]);
}
}
return result;}
// Function to print the result list function printArr(arr) { console.log(arr.join(" ")); }
// Representation of given N-ary tree
// 11
// / |
// 21 29 90
// / / \
// 18 10 12 77
let root = new Node(11);
root.children.push(new Node(21));
root.children.push(new Node(29));
root.children.push(new Node(90));
root.children[0].children.push(new Node(18));
root.children[1].children.push(new Node(10));
root.children[1].children.push(new Node(12));
root.children[2].children.push(new Node(77));
let result = nAryPreorderTraversal(root); printArr(result);
`
Output
11 21 18 29 10 12 90 77
**Time Complexity: O(n), aseach node is processed once
**Space Complexity: O(n), as in worst case when all nodes are in stack