Related Articles
Iterative Preorder Traversal of an N-ary Tree
• Difficulty Level : Medium
• Last Updated : 24 Dec, 2020

Given a K-ary Tree. The task is to write an iterative 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```

Preorder Traversal of an N-ary Tree is similar to the preorder traversal of 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. If Top of the stack is a leaf node then remove it from the stack
2. If Top of the stack is Parent with children:
• As soon as an unvisited child is found(left to right sequence), Push it to Stack and Store it in
Auxillary List and mark the following child as visited.Then, start again from Case-1, to explore this newly visited child.
• If all Child nodes from left to right of a Parent has been visited then remove the Parent from
the stack.

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:

## C++

 `// C++ program for Iterative Preorder` `// Traversal of N-ary Tree.` `// Preorder{ Root, print children` `// from left to right.` `#include ` `using` `namespace` `std;`   `// Node Structure of K-ary Tree` `class` `NewNode ` `{` `    ``public``:` `    `  `        ``int` `key;` `        `  `        ``// All children are stored in a list` `        ``vector child;` `        ``NewNode(``int` `val) : key(val) {}` `};`   `// Utility function to print the` `// preorder of the given K-Ary Tree` `void` `preorderTraversal(NewNode *root)` `{` `    ``stack Stack;` `    `  `    ``// 'Preorder'-> contains all the` `    ``// visited nodes` `    ``vector<``int``> Preorder;` `    `  `    ``Preorder.push_back(root->key);` `    ``Stack.push(root);` `    `  `    ``while` `(!Stack.empty()) ` `    ``{` `        `  `        ``// 'Flag' checks whether all the child` `        ``// nodes have been visited.` `        ``int` `flag = 0;` `        `  `        ``// CASE 1- If Top of the stack is a leaf` `        ``// node then remove it from the stack{` `        ``if` `(Stack.top()->child.size() == 0) ` `        ``{` `            ``Stack.pop();` `        ``}` `        `  `        ``// CASE 2- If Top of the stack is` `        ``// Parent with children{` `        ``else` `        ``{` `            ``NewNode *Par = Stack.top();` `            `  `            ``// a)As soon as an unvisited child is` `            ``// found(left to right sequence),` `            ``// Push it to Stack and Store it in` `            ``// Auxillary List(Marked Visited)` `            ``// Start Again from Case-1, to explore` `            ``// this newly visited child` `            ``for``(``int` `i = 0; i < Par->child.size(); i++)` `            ``{` `                ``if` `(find(Preorder.begin(), Preorder.end(),` `                    ``Par->child[i]->key) == Preorder.end())` `                ``{` `                    ``flag = 1;` `                    ``Stack.push(Par->child[i]);` `                    ``Preorder.push_back(Par->child[i]->key);` `                    ``break``;` `                ``}` `            ``}` `            `  `            ``// b)If all Child nodes from left to right` `            ``// of a Parent have been visited` `            ``// then remove the parent from the stack.` `            ``if` `(flag == 0)` `            ``{` `                ``Stack.pop();` `            ``}` `        ``}` `    ``}` `    ``for``(``auto` `i : Preorder)` `    ``{` `        ``cout << i << ``" "``;` `    ``}` `    ``cout << endl;` `}`   `// Driver Code` `int` `main() ` `{` `    `  `    ``// input nodes` `    ``/*` `             ``1` `          ``/  |  \` `         ``/   |   \` `        ``2    3    4` `       ``/ \      / | \` `      ``/   \    7  8  9` `     ``5     6` `    ``/    / | \` `   ``10   11 12 13` `    ``*/` `    `  `    ``NewNode *root = ``new` `NewNode(1);` `    ``root->child.push_back(``new` `NewNode(2));` `    ``root->child.push_back(``new` `NewNode(3));` `    ``root->child.push_back(``new` `NewNode(4));` `    `  `    ``root->child->child.push_back(``new` `NewNode(5));` `    ``root->child->child->child.push_back(``new` `NewNode(10));` `    ``root->child->child.push_back(``new` `NewNode(6));` `    ``root->child->child->child.push_back(``new` `NewNode(11));` `    ``root->child->child->child.push_back(``new` `NewNode(12));` `    ``root->child->child->child.push_back(``new` `NewNode(13));` `    ``root->child->child.push_back(``new` `NewNode(7));` `    ``root->child->child.push_back(``new` `NewNode(8));` `    ``root->child->child.push_back(``new` `NewNode(9));` `    `  `    ``preorderTraversal(root);` `}`   `// This code is contributed by sanjeev2552`

## Python3

 `# Python3 program for Iterative Preorder` `# Traversal of N-ary Tree.` `# Preorder: Root, print children` `# from left to right.`   `from` `collections ``import` `deque`   `# Node Structure of K-ary Tree` `class` `NewNode():`   `    ``def` `__init__(``self``, val):` `        ``self``.key ``=` `val` `        ``# all children are stored in a list` `        ``self``.child ``=``[]`     `# Utility function to print the` `# preorder of the given K-Ary Tree` `def` `preorderTraversal(root):`   `    ``Stack ``=` `deque([])` `    ``# 'Preorder'-> contains all the` `    ``# visited nodes.` `    ``Preorder ``=``[]` `    ``Preorder.append(root.key)` `    ``Stack.append(root)` `    ``while` `len``(Stack)>``0``:` `        ``# 'Flag' checks whether all the child` `        ``# nodes have been visited.` `        ``flag ``=` `0` `        ``# CASE 1- If Top of the stack is a leaf` `        ``# node then remove it from the stack:` `        ``if` `len``((Stack[``len``(Stack)``-``1``]).child)``=``=` `0``:` `            ``X ``=` `Stack.pop()` `            ``# CASE 2- If Top of the stack is` `            ``# Parent with children:` `        ``else``:` `            ``Par ``=` `Stack[``len``(Stack)``-``1``]` `        ``# a)As soon as an unvisited child is ` `        ``# found(left to right sequence),` `        ``# Push it to Stack and Store it in ` `        ``# Auxillary List(Marked Visited)` `        ``# Start Again from Case-1, to explore` `        ``# this newly visited child` `        ``for` `i ``in` `range``(``0``, ``len``(Par.child)):` `            ``if` `Par.child[i].key ``not` `in` `Preorder:` `                ``flag ``=` `1` `                ``Stack.append(Par.child[i])` `                ``Preorder.append(Par.child[i].key)` `                ``break``;` `                ``# b)If all Child nodes from left to right` `                ``# of a Parent have been visited` `                ``# then remove the parent from the stack.` `        ``if` `flag ``=``=` `0``:` `            ``Stack.pop()` `    ``print``(Preorder)`   `# Execution Start From here` `if` `__name__``=``=``'__main__'``:` `# input nodes` `                ``'''` `                `  `                  ``1` `               ``/  |  \` `              ``/   |   \` `             ``2    3    4` `            ``/ \      / | \` `           ``/   \    7  8  9` `          ``5     6    ` `         ``/    / | \ ` `        ``10   11 12 13` `        `  `                ``'''` `                `  `root ``=` `NewNode(``1``)` `root.child.append(NewNode(``2``))` `root.child.append(NewNode(``3``))` `root.child.append(NewNode(``4``)) ` `root.child[``0``].child.append(NewNode(``5``)) ` `root.child[``0``].child[``0``].child.append(NewNode(``10``)) ` `root.child[``0``].child.append(NewNode(``6``)) ` `root.child[``0``].child[``1``].child.append(NewNode(``11``))` `root.child[``0``].child[``1``].child.append(NewNode(``12``))` `root.child[``0``].child[``1``].child.append(NewNode(``13``)) ` `root.child[``2``].child.append(NewNode(``7``))` `root.child[``2``].child.append(NewNode(``8``))` `root.child[``2``].child.append(NewNode(``9``))` `    `  `preorderTraversal(root)`

Output:

`[1, 2, 5, 10, 6, 11, 12, 13, 3, 4, 7, 8, 9]`

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.

My Personal Notes arrow_drop_up
Recommended Articles
Page :