Preorder Traversal of N-ary Tree Without Recursion in C++

C++Server Side ProgrammingProgramming

In this problem, we are given an N-ary Tree. Our task is to print the preorder traversal of the tree.

First, let’s learn some basic terminologies,

N-ary Tree is a tree in which all nodes can have at max N child nodes. Example 2-ary (binary) tree has max 2 child nodes.

Preorder Traversal is a way to traverse nodes of the tree. In this we will first traverse root node then left child and then the right child.

Let’s take an example to understand our problem

Preorder traversal :

To solve this problem, we have to use the stack data structure. We will first push the root node to the stack. Then pop it and print it. For every popped node, we will push child nodes of the stack from the right child to the left child. Then pop when all child nodes are pushed. Repeat this process until the stack is empty.

Program to show the implementation of our solution


 Live Demo

#include <bits/stdc++.h>
using namespace std;
struct Node {
   int key;
   vector<Node*> child;
Node* insertNode(int key){
   Node* temp = new Node;
   temp->key = key;
   return temp;
void preOrderTraversal(struct Node* root){
   stack<Node*> tree;
   while (!tree.empty()) {
      Node* curr =;
      vector<Node*>::iterator it = curr->child.end();
      while (it != curr->child.begin()) {
int main(){
   Node* root = insertNode(12);
   cout<<"PreOrder Traversal of the tree is :\n";
   return 0;


PreOrder Traversal of the tree is :
12   15   14   25   99   4   11   7   19
Published on 03-Feb-2020 16:21:55