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++ // C++ program for Iterative Preorder // Traversal of N-ary Tree. // Preorder{ Root, print children // from left to right. #include <bits/stdc++.h> using namespace std; // Node Structure of K-ary Tree class NewNode { public: int key; // All children are stored in a list vector<NewNode*> child; NewNode(int val) : key(val) { } }; // Utility function to print the // preorder of the given K-Ary Tree void preorderTraversal(NewNode* root) { stack<NewNode*> Stack; // 'Preorder'-> contains all the // visited nodes vector<int> Preorder; Stack.push(root); while (!Stack.empty()) { NewNode* temp = Stack.top(); Stack.pop(); // store the key in preorder vector(visited list) Preorder.push_back(temp->key); // Push all of the child nodes of temp into // the stack from right to left. for (int i = temp->child.size() - 1; i >= 0; i--) { Stack.push(temp->child[i]); } } 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[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); } // This code is contributed by sarangiswastika5
Java // Java program for Iterative Preorder // Traversal of N-ary Tree. // Preorder{ Root, print children // from left to right. import java.util.*; public class gfg2 { // Node Structure of K-ary Tree static class Node { int key; // All children are stored in a list ArrayList<Node> child; Node(int val) { key = val; child = new ArrayList<>(); } }; // Utility function to print the // preorder of the given K-Ary Tree static void preorderTraversal(Node root) { Stack<Node> stack = new Stack<>(); // 'Preorder'-> contains all the // visited nodes ArrayList<Integer> Preorder = new ArrayList<>(); stack.push(root); while (!stack.isEmpty()) { Node temp = stack.peek(); stack.pop(); // store the key in preorder vector(visited // list) Preorder.add(temp.key); // Push all of the child nodes of temp into // the stack from right to left. 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(); } // Driver Code public static void main(String[] args) { // input nodes /* 1 / | \ / | \ 2 3 4 / \ / | \ / \ 7 8 9 5 6 / / | \ 10 11 12 13 */ 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); } } // This code is contributed by karandeep1234
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 # Auxiliary 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)
C# // C# program for Iterative Preorder // Traversal of N-ary Tree. // Preorder{ Root, print children // from left to right. using System; using System.Collections; using System.Collections.Generic; class gfg2 { // Node Structure of K-ary Tree public class Node { public int key; // All children are stored in a list public List<Node> child; public Node(int val) { key = val; child = new List<Node>(); } }; // Utility function to print the // preorder of the given K-Ary Tree static void preorderTraversal(Node root) { Stack<Node> stack = new Stack<Node>(); // 'Preorder'-> contains all the // visited nodes List<int> Preorder = new List<int>(); stack.Push(root); while (stack.Count != 0) { Node temp = stack.Peek(); stack.Pop(); // store the key in preorder vector(visited // list) Preorder.Add(temp.key); // Push all of the child nodes of temp into // the stack from right to left. 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(); } // Driver Code public static void Main(string[] args) { // input nodes /* 1 / | \ / | \ 2 3 4 / \ / | \ / \ 7 8 9 5 6 / / | \ 10 11 12 13 */ 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); } } // This code is contributed by karandeep1234
JavaScript // Node Structure of K-ary Tree class NewNode { constructor(val) { this.key = val; // all children are stored in an array this.child = []; } } // Utility function to print the // preorder of the given K-Ary Tree function preorderTraversal(root) { let stack = []; // 'Preorder'-> contains all the // visited nodes. let preorder = []; preorder.push(root.key); stack.push(root); while (stack.length > 0) { // 'flag' checks whether all the child // nodes have been visited. let flag = 0; // CASE 1- If Top of the stack is a leaf // node then remove it from the stack: if (stack[stack.length - 1].child.length === 0) { let x = stack.pop(); // CASE 2- If Top of the stack is // Parent with children: } else { let par = stack[stack.length - 1]; // a)As soon as an unvisited child is // found(left to right sequence), // Push it to Stack and Store it in // Auxiliary List(Marked Visited) // Start Again from Case-1, to explore // this newly visited child 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; } // 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(); } } } document.write(preorder); } // Execution Start From here // input nodes /* 1 / | / | 2 3 4 / \ / | / \ 7 8 9 5 6 / / | \ 10 11 12 13 */ 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)
Output1 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++ // C++ program for Recursive Preorder Traversal of N-ary // Tree. #include <bits/stdc++.h> using namespace std; // Node Structure of K-ary Tree struct Node { char val; vector<Node*> children; }; // Utility function to create a new tree node Node* newNode(int key) { Node* temp = new Node; temp->val = key; return temp; } // Recursive function to print the // preorder of the given K-Ary Tree 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; } // Function to print preorder list void preorderTraversal(Node* root) { vector<int> v; fun(root, v); for (auto it : v) cout << it << " "; } // Driver Code int main() { // input nodes /* 1 / | \ / | \ 2 3 4 / \ / | \ 5 6 7 8 9 / / | \ 10 11 12 13 */ 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); } // This code is contributed by Aditya Kumar (adityakumar129)
Python3 # Python3 program for Recursive Preorder Traversal of N-ary Tree # Node Structure of K-ary Tree class Node: def __init__(self, val): self.val = val self.children = [] # Utility function to create a new tree node def newNode(key): temp = Node(key) return temp # Recursive function to print the preorder of the given K-Ary Tree 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 # Function to print preorder list def preorderTraversal(root): v = [] fun(root, v) for it in v: print(it, end=" ") # Input nodes ''' 1 / | \ / | \ 2 3 4 / \ / | \ 5 6 7 8 9 / / | \ 10 11 12 13 ''' 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) # This code is contributed by lokeshpotta20.
C# using System; using System.Collections; using System.Collections.Generic; public class Gfg { // Node Structure of K-ary Tree public class Node { public int val; public List<Node> children; public Node(int val) { this.val=val; this.children=new List<Node>(); } }; // Utility function to create a new tree node /*Node* newNode(int key) { Node* temp = new Node; temp.val = key; return temp; }*/ // Recursive function to print the // preorder of the given K-Ary Tree 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; } // Function to print preorder list static void preorderTraversal(Node root) { List<int> v=new List<int>(); fun(root, v); foreach (int i in v) Console.Write(i + " "); } // Driver Code public static void Main(string[] args) { // input nodes /* 1 / | \ / | \ 2 3 4 / \ / | \ 5 6 7 8 9 / / | \ 10 11 12 13 */ 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); } } // This code is contributed by poojaagarwal2.
JavaScript // Javascript program for Recursive Preorder Traversal of N-ary // Tree. // Node Structure of K-ary Tree class Node { /*char val; vector<Node*> children;*/ constructor(val) { this.val=val; this.children=new Array(); } } // Utility function to create a new tree node /*Node* newNode(int key) { Node* temp = new Node; temp.val = key; return temp; }*/ // Recursive function to print the // preorder of the given K-Ary Tree 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 to print preorder list function preorderTraversal( root) { v=new Array(); fun(root, v); for (let it of v) console.log(it + " "); } // Driver Code // input nodes /* 1 / | \ / | \ 2 3 4 / \ / | \ 5 6 7 8 9 / / | \ 10 11 12 13 */ 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); // This code is contributed by ratiagrawal.
Java // Java program for Recursive Preorder Traversal of N-ary // Tree. import java.io.*; import java.util.*; // Node Structure of K-ary Tree class Node { int val; List<Node> children; Node(int val) { this.val = val; this.children = new ArrayList<>(); } } class GFG { // Recursive function to print the preorder of the given // K-Ary Tree 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); } } // Function to print preorder list 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) { // input nodes /* 1 / | \ / | \ 2 3 4 / \ /|\ 5 6 7 8 9 / / | \ 10 11 12 13 */ 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); } } // This code is contributed by karthik
Output1 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.
Similar Reads
Introduction to Generic Trees (N-ary Trees) Generic trees are a collection of nodes where each node is a data structure that consists of records and a list of references to its children(duplicate references are not allowed). Unlike the linked list, each node stores the address of multiple nodes. Every node stores address of its children and t
5 min read
What is Generic Tree or N-ary Tree? Generic tree or an N-ary tree is a versatile data structure used to organize data hierarchically. Unlike binary trees that have at most two children per node, generic trees can have any number of child nodes. This flexibility makes them suitable for representing hierarchical data where each node can
4 min read
N-ary Tree Traversals
Inorder traversal of an N-ary TreeGiven an N-ary tree containing, the task is to print the inorder traversal of the tree. Examples:Â Input: N = 3Â Â Output: 5 6 2 7 3 1 4Input: N = 3Â Â Output: 2 3 5 1 4 6Â Approach: The inorder traversal of an N-ary tree is defined as visiting all the children except the last then the root and finall
6 min read
Preorder Traversal of an N-ary TreeGiven 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 O
14 min read
Iterative Postorder Traversal of N-ary TreeGiven an N-ary tree, the task is to find the post-order traversal of the given tree iteratively.Examples: Input: 1 / | \ 3 2 4 / \ 5 6 Output: [5, 6, 3, 2, 4, 1] Input: 1 / \ 2 3 Output: [2, 3, 1] Approach:We have already discussed iterative post-order traversal of binary tree using one stack. We wi
10 min read
Level Order Traversal of N-ary TreeGiven an N-ary Tree. The task is to print the level order traversal of the tree where each level will be in a new line. Examples: Input: Image Output: 13 2 45 6Explanation: At level 1: only 1 is present.At level 2: 3, 2, 4 is presentAt level 3: 5, 6 is present Input: Image Output: 12 3 4 56 7 8 9 10
11 min read
ZigZag Level Order Traversal of an N-ary TreeGiven a Generic Tree consisting of n nodes, the task is to find the ZigZag Level Order Traversal of the given tree.Note: A generic tree is a tree where each node can have zero or more children nodes. Unlike a binary tree, which has at most two children per node (left and right), a generic tree allow
8 min read
Depth of an N-Ary tree Given an n-ary tree containing positive node values, the task is to find the depth of the tree.Note: An n-ary tree is a tree where each node can have zero or more children nodes. Unlike a binary tree, which has at most two children per node (left and right), the n-ary tree allows for multiple branch
5 min read
Mirror of n-ary Tree Given a Tree where every node contains variable number of children, convert the tree to its mirror. Below diagram shows an example. We strongly recommend you to minimize your browser and try this yourself first. Node of tree is represented as a key and a variable sized array of children pointers. Th
9 min read
Insertion in n-ary tree in given order and Level order traversal Given a set of parent nodes where the index of the array is the child of each Node value, the task is to insert the nodes as a forest(multiple trees combined together) where each parent could have more than two children. After inserting the nodes, print each level in a sorted format. Example: Input:
10 min read
Diameter of an N-ary tree The diameter of an N-ary tree is the longest path present between any two nodes of the tree. These two nodes must be two leaf nodes. The following examples have the longest path[diameter] shaded. Example 1: Example 2: Prerequisite: Diameter of a binary tree. The path can either start from one of th
15+ min read
Sum of all elements of N-ary Tree Given an n-ary tree consisting of n nodes, the task is to find the sum of all the elements in the given n-ary tree.Example:Input:Output: 268Explanation: The sum of all the nodes is 11 + 21 + 29 + 90 + 18 + 10 + 12 + 77 = 268Input:Output: 360Explanation: The sum of all the nodes is 81 + 26 + 23 + 49
5 min read
Serialize and Deserialize an N-ary Tree Given an N-ary tree where every node has the most N children. How to serialize and deserialize it? Serialization is to store a tree in a file so that it can be later restored. The structure of the tree must be maintained. Deserialization is reading the tree back from the file. This post is mainly an
11 min read
Easy problems on n-ary Tree
Check if the given n-ary tree is a binary treeGiven an n-ary tree consisting of n nodes, the task is to check whether the given tree is binary or not.Note: An n-ary tree is a tree where each node can have zero or more children nodes. Unlike a binary tree, which has at most two children per node (left and right), the n-ary tree allows for multip
6 min read
Largest element in an N-ary TreeGiven an n-ary tree containing positive node values, the task is to find the node with the largest value in the given n-ary tree.Note: An n-ary tree is a tree where each node can have zero or more children nodes. Unlike a binary tree, which has at most two children per node (left and right), the n-a
5 min read
Second Largest element in n-ary treeGiven an n-ary tree containing positive node values, the task is to find the node with the second largest value in the given n-ary tree. If there is no second largest node return -1.Note: An n-ary tree is a tree where each node can have zero or more children nodes. Unlike a binary tree, which has at
7 min read
Number of children of given node in n-ary TreeGiven a node x, find the number of children of x(if it exists) in the given n-ary tree. Example : Input : x = 50 Output : 3 Explanation : 50 has 3 children having values 40, 100 and 20. Approach : Initialize the number of children as 0.For every node in the n-ary tree, check if its value is equal to
7 min read
Number of nodes greater than a given value in n-ary treeGiven a n-ary tree and a number x, find and return the number of nodes which are greater than x. Example: In the given tree, x = 7 Number of nodes greater than x are 4. Approach: The idea is maintain a count variable initialize to 0. Traverse the tree and compare root data with x. If root data is gr
6 min read
Check mirror in n-ary treeGiven two n-ary trees, determine whether they are mirror images of each other. Each tree is described by e edges, where e denotes the number of edges in both trees. Two arrays A[]and B[] are provided, where each array contains 2*e space-separated values representing the edges of both trees. Each edg
11 min read
Replace every node with depth in N-ary Generic TreeGiven an array arr[] representing a Generic(N-ary) tree. The task is to replace the node data with the depth(level) of the node. Assume level of root to be 0. Array Representation: The N-ary tree is serialized in the array arr[] using level order traversal as described below:Â Â The input is given as
15+ min read
Preorder Traversal of N-ary Tree Without RecursionGiven 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
6 min read
Maximum value at each level in an N-ary TreeGiven a N-ary Tree consisting of nodes valued in the range [0, N - 1] and an array arr[] where each node i is associated to value arr[i], the task is to print the maximum value associated with any node at each level of the given N-ary Tree. Examples: Input: N = 8, Edges[][] = {{0, 1}, {0, 2}, {0, 3}
9 min read
Replace each node in given N-ary Tree with sum of all its subtreesGiven an N-ary tree. The task is to replace the values of each node with the sum of all its subtrees and the node itself. Examples Input: 1 / | \ 2 3 4 / \ \ 5 6 7Output: Initial Pre-order Traversal: 1 2 5 6 7 3 4 Final Pre-order Traversal: 28 20 5 6 7 3 4 Explanation: Value of each node is replaced
8 min read
Path from the root node to a given node in an N-ary TreeGiven an integer N and an N-ary Tree of the following form: Every node is numbered sequentially, starting from 1, till the last level, which contains the node N.The nodes at every odd level contains 2 children and nodes at every even level contains 4 children. The task is to print the path from the
10 min read
Determine the count of Leaf nodes in an N-ary treeGiven the value of 'N' and 'I'. Here, I represents the number of internal nodes present in an N-ary tree and every node of the N-ary can either have N childs or zero child. The task is to determine the number of Leaf nodes in n-ary tree. Examples: Input : N = 3, I = 5 Output : Leaf nodes = 11 Input
4 min read
Remove all leaf nodes from a Generic Tree or N-ary TreeGiven an n-ary tree containing positive node values, the task is to delete all the leaf nodes from the tree and print preorder traversal of the tree after performing the deletion.Note: An n-ary tree is a tree where each node can have zero or more children nodes. Unlike a binary tree, which has at mo
6 min read
Maximum level sum in N-ary TreeGiven an N-ary Tree consisting of nodes valued [1, N] and an array value[], where each node i is associated with value[i], the task is to find the maximum of sum of all node values of all levels of the N-ary Tree. Examples: Input: N = 8, Edges[][2] = {{0, 1}, {0, 2}, {0, 3}, {1, 4}, {1, 5}, {3, 6},
9 min read
Number of leaf nodes in a perfect N-ary tree of height KFind the number of leaf nodes in a perfect N-ary tree of height K. Note: As the answer can be very large, return the answer modulo 109+7. Examples: Input: N = 2, K = 2Output: 4Explanation: A perfect Binary tree of height 2 has 4 leaf nodes. Input: N = 2, K = 1Output: 2Explanation: A perfect Binary t
4 min read
Print all root to leaf paths of an N-ary treeGiven an N-Ary tree, the task is to print all root to leaf paths of the given N-ary Tree. Examples: Input: 1 / \ 2 3 / / \ 4 5 6 / \ 7 8 Output:1 2 41 3 51 3 6 71 3 6 8 Input: 1 / | \ 2 5 3 / \ \ 4 5 6Output:1 2 41 2 51 51 3 6 Approach: The idea to solve this problem is to start traversing the N-ary
7 min read
Minimum distance between two given nodes in an N-ary treeGiven a N ary Tree consisting of N nodes, the task is to find the minimum distance from node A to node B of the tree. Examples: Input: 1 / \ 2 3 / \ / \ \4 5 6 7 8A = 4, B = 3Output: 3Explanation: The path 4->2->1->3 gives the minimum distance from A to B. Input: 1 / \ 2 3 / \ \ 6 7 8A = 6,
11 min read
Average width in a N-ary treeGiven a Generic Tree consisting of N nodes, the task is to find the average width for each node present in the given tree. The average width for each node can be calculated by the ratio of the total number of nodes in that subtree(including the node itself) to the total number of levels under that n
8 min read
Maximum width of an N-ary treeGiven an N-ary tree, the task is to find the maximum width of the given tree. The maximum width of a tree is the maximum of width among all levels. Examples: Input: 4 / | \ 2 3 -5 / \ /\ -1 3 -2 6 Output: 4 Explanation: Width of 0th level is 1. Width of 1st level is 3. Width of 2nd level is 4. There
9 min read