Preorder Traversal of an N-ary Tree
Last Updated :
22 Feb, 2023
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:
- Pop the top node from the stack – Top from the stack and insert it into the visited list of nodes.
- 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:
C++
#include <bits/stdc++.h>
using namespace std;
class NewNode {
public :
int key;
vector<NewNode*> child;
NewNode( int val)
: key(val)
{
}
};
void preorderTraversal(NewNode* root)
{
stack<NewNode*> Stack;
vector< int > Preorder;
Stack.push(root);
while (!Stack.empty()) {
NewNode* temp = Stack.top();
Stack.pop();
Preorder.push_back(temp->key);
for ( int i = temp->child.size() - 1; i >= 0; i--) {
Stack.push(temp->child[i]);
}
}
for ( auto i : Preorder) {
cout << i << " " ;
}
cout << endl;
}
int main()
{
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[0]->child.push_back( new NewNode(5));
root->child[0]->child[0]->child.push_back(
new NewNode(10));
root->child[0]->child.push_back( new NewNode(6));
root->child[0]->child[1]->child.push_back(
new NewNode(11));
root->child[0]->child[1]->child.push_back(
new NewNode(12));
root->child[0]->child[1]->child.push_back(
new NewNode(13));
root->child[2]->child.push_back( new NewNode(7));
root->child[2]->child.push_back( new NewNode(8));
root->child[2]->child.push_back( new NewNode(9));
preorderTraversal(root);
}
|
Java
import java.util.*;
public class gfg2 {
static class Node {
int key;
ArrayList<Node> child;
Node( int val)
{
key = val;
child = new ArrayList<>();
}
};
static void preorderTraversal(Node root)
{
Stack<Node> stack = new Stack<>();
ArrayList<Integer> Preorder = new ArrayList<>();
stack.push(root);
while (!stack.isEmpty()) {
Node temp = stack.peek();
stack.pop();
Preorder.add(temp.key);
for ( int i = temp.child.size() - 1 ; i >= 0 ;
i--) {
stack.push(temp.child.get(i));
}
}
for (Integer i : Preorder) {
System.out.print(i + " " );
}
System.out.println();
}
public static void main(String[] args)
{
Node root = new Node( 1 );
root.child.add( new Node( 2 ));
root.child.add( new Node( 3 ));
root.child.add( new Node( 4 ));
root.child.get( 0 ).child.add( new Node( 5 ));
root.child.get( 0 ).child.get( 0 ).child.add(
new Node( 10 ));
root.child.get( 0 ).child.add( new Node( 6 ));
root.child.get( 0 ).child.get( 1 ).child.add(
new Node( 11 ));
root.child.get( 0 ).child.get( 1 ).child.add(
new Node( 12 ));
root.child.get( 0 ).child.get( 1 ).child.add(
new Node( 13 ));
root.child.get( 2 ).child.add( new Node( 7 ));
root.child.get( 2 ).child.add( new Node( 8 ));
root.child.get( 2 ).child.add( new Node( 9 ));
preorderTraversal(root);
}
}
|
Python3
from collections import deque
class NewNode():
def __init__( self , val):
self .key = val
self .child = []
def preorderTraversal(root):
Stack = deque([])
Preorder = []
Preorder.append(root.key)
Stack.append(root)
while len (Stack) > 0 :
flag = 0
if len ((Stack[ len (Stack) - 1 ]).child) = = 0 :
X = Stack.pop()
else :
Par = Stack[ len (Stack) - 1 ]
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
if flag = = 0 :
Stack.pop()
print (Preorder)
if __name__ = = '__main__' :
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)
|
C#
using System;
using System.Collections;
using System.Collections.Generic;
class gfg2 {
public class Node {
public int key;
public List<Node> child;
public Node( int val)
{
key = val;
child = new List<Node>();
}
};
static void preorderTraversal(Node root)
{
Stack<Node> stack = new Stack<Node>();
List< int > Preorder = new List< int >();
stack.Push(root);
while (stack.Count != 0) {
Node temp = stack.Peek();
stack.Pop();
Preorder.Add(temp.key);
for ( int i = temp.child.Count - 1; i >= 0;
i--) {
stack.Push(temp.child[i]);
}
}
foreach ( int i in Preorder)
{
Console.Write(i + " " );
}
Console.WriteLine();
}
public static void Main( string [] args)
{
Node root = new Node(1);
root.child.Add( new Node(2));
root.child.Add( new Node(3));
root.child.Add( new Node(4));
root.child[0].child.Add( new Node(5));
root.child[0].child[0].child.Add( new Node(10));
root.child[0].child.Add( new Node(6));
root.child[0].child[1].child.Add( new Node(11));
root.child[0].child[1].child.Add( new Node(12));
root.child[0].child[1].child.Add( new Node(13));
root.child[2].child.Add( new Node(7));
root.child[2].child.Add( new Node(8));
root.child[2].child.Add( new Node(9));
preorderTraversal(root);
}
}
|
Javascript
class NewNode {
constructor(val) {
this .key = val;
this .child = [];
}
}
function preorderTraversal(root) {
let stack = [];
let preorder = [];
preorder.push(root.key);
stack.push(root);
while (stack.length > 0) {
let flag = 0;
if (stack[stack.length - 1].child.length === 0) {
let x = stack.pop();
} else {
let par = stack[stack.length - 1];
for (let i = 0; i < par.child.length; i++) {
if (!preorder.includes(par.child[i].key)) {
flag = 1;
stack.push(par.child[i]);
preorder.push(par.child[i].key);
break ;
}
}
if (flag === 0) {
stack.pop();
}
}
}
document.write(preorder);
}
let root = new NewNode(1);
root.child.push( new NewNode(2));
root.child.push( new NewNode(3));
root.child.push( new NewNode(4));
root.child[0].child.push( new NewNode(5));
root.child[0].child[0].child.push( new NewNode(10));
root.child[0].child.push( new NewNode(6));
root.child[0].child[1].child.push( new NewNode(11));
root.child[0].child[1].child.push( new NewNode(12));
root.child[0].child[1].child.push( new NewNode(13));
root.child[2].child.push( new NewNode(7))
root.child[2].child.push( new NewNode(8))
root.child[2].child.push( new NewNode(9))
preorderTraversal(root)
|
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:
C++
#include <bits/stdc++.h>
using namespace std;
struct Node {
char val;
vector<Node*> children;
};
Node* newNode( int key)
{
Node* temp = new Node;
temp->val = key;
return temp;
}
void fun(Node* root, vector< int >& v)
{
if (root == NULL) {
return ;
}
v.push_back(root->val);
for ( int i = 0; i < root->children.size(); i++) {
fun(root->children[i], v);
}
return ;
}
void preorderTraversal(Node* root)
{
vector< int > v;
fun(root, v);
for ( auto it : v)
cout << it << " " ;
}
int main()
{
Node* root = newNode(1);
root->children.push_back(newNode(2));
root->children.push_back(newNode(3));
root->children.push_back(newNode(4));
root->children[0]->children.push_back(newNode(5));
root->children[0]->children[0]->children.push_back(
newNode(10));
root->children[0]->children.push_back(newNode(6));
root->children[0]->children[1]->children.push_back(
newNode(11));
root->children[0]->children[1]->children.push_back(
newNode(12));
root->children[0]->children[1]->children.push_back(
newNode(13));
root->children[2]->children.push_back(newNode(7));
root->children[2]->children.push_back(newNode(8));
root->children[2]->children.push_back(newNode(9));
preorderTraversal(root);
}
|
Python3
class Node:
def __init__( self , val):
self .val = val
self .children = []
def newNode(key):
temp = Node(key)
return temp
def fun(root, v):
if root is None :
return
v.append(root.val)
for i in range ( len (root.children)):
fun(root.children[i], v)
return
def preorderTraversal(root):
v = []
fun(root, v)
for it in v:
print (it, end = " " )
root = newNode( 1 )
root.children.append(newNode( 2 ))
root.children.append(newNode( 3 ))
root.children.append(newNode( 4 ))
root.children[ 0 ].children.append(newNode( 5 ))
root.children[ 0 ].children[ 0 ].children.append(newNode( 10 ))
root.children[ 0 ].children.append(newNode( 6 ))
root.children[ 0 ].children[ 1 ].children.append(newNode( 11 ))
root.children[ 0 ].children[ 1 ].children.append(newNode( 12 ))
root.children[ 0 ].children[ 1 ].children.append(newNode( 13 ))
root.children[ 2 ].children.append(newNode( 7 ))
root.children[ 2 ].children.append(newNode( 8 ))
root.children[ 2 ].children.append(newNode( 9 ))
preorderTraversal(root)
|
C#
using System;
using System.Collections;
using System.Collections.Generic;
public class Gfg
{
public class Node {
public int val;
public List<Node> children;
public Node( int val)
{
this .val=val;
this .children= new List<Node>();
}
};
static void fun(Node root, List< int > v)
{
if (root == null ) {
return ;
}
v.Add(root.val);
for ( int i = 0; i < root.children.Count; i++) {
fun(root.children[i], v);
}
return ;
}
static void preorderTraversal(Node root)
{
List< int > v= new List< int >();
fun(root, v);
foreach ( int i in v)
Console.Write(i + " " );
}
public static void Main( string [] args)
{
Node root = new Node(1);
root.children.Add( new Node(2));
root.children.Add( new Node(3));
root.children.Add( new Node(4));
root.children[0].children.Add( new Node(5));
root.children[0].children[0].children.Add(
new Node(10));
root.children[0].children.Add( new Node(6));
root.children[0].children[1].children.Add(
new Node(11));
root.children[0].children[1].children.Add(
new Node(12));
root.children[0].children[1].children.Add(
new Node(13));
root.children[2].children.Add( new Node(7));
root.children[2].children.Add( new Node(8));
root.children[2].children.Add( new Node(9));
preorderTraversal(root);
}
}
|
Javascript
class Node {
constructor(val)
{
this .val=val;
this .children= new Array();
}
}
function fun( root, v)
{
if (root == null ) {
return ;
}
v.push(root.val);
for (let i = 0; i < root.children.length; i++) {
fun(root.children[i], v);
}
return ;
}
function preorderTraversal( root)
{
v= new Array();
fun(root, v);
for (let it of v)
console.log(it + " " );
}
let root = new Node(1);
root.children.push( new Node(2));
root.children.push( new Node(3));
root.children.push( new Node(4));
root.children[0].children.push( new Node(5));
root.children[0].children[0].children.push(
new Node(10));
root.children[0].children.push( new Node(6));
root.children[0].children[1].children.push(
new Node(11));
root.children[0].children[1].children.push(
new Node(12));
root.children[0].children[1].children.push(
new Node(13));
root.children[2].children.push( new Node(7));
root.children[2].children.push( new Node(8));
root.children[2].children.push( new Node(9));
preorderTraversal(root);
|
Java
import java.io.*;
import java.util.*;
class Node {
int val;
List<Node> children;
Node( int val)
{
this .val = val;
this .children = new ArrayList<>();
}
}
class GFG {
static void fun(Node root, List<Integer> v)
{
if (root == null ) {
return ;
}
v.add(root.val);
for ( int i = 0 ; i < root.children.size(); i++) {
fun(root.children.get(i), v);
}
}
static void preorderTraversal(Node root)
{
List<Integer> v = new ArrayList<>();
fun(root, v);
for ( int i : v)
System.out.print(i + " " );
}
public static void main(String[] args)
{
Node root = new Node( 1 );
root.children.add( new Node( 2 ));
root.children.add( new Node( 3 ));
root.children.add( new Node( 4 ));
root.children.get( 0 ).children.add( new Node( 5 ));
root.children.get( 0 ).children.get( 0 ).children.add(
new Node( 10 ));
root.children.get( 0 ).children.add( new Node( 6 ));
root.children.get( 0 ).children.get( 1 ).children.add(
new Node( 11 ));
root.children.get( 0 ).children.get( 1 ).children.add(
new Node( 12 ));
root.children.get( 0 ).children.get( 1 ).children.add(
new Node( 13 ));
root.children.get( 2 ).children.add( new Node( 7 ));
root.children.get( 2 ).children.add( new Node( 8 ));
root.children.get( 2 ).children.add( new Node( 9 ));
preorderTraversal(root);
}
}
|
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.
Share your thoughts in the comments
Please Login to comment...