Replace every node with depth in N-ary Generic Tree
Last Updated :
27 May, 2024
Given 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 a level order traversal of N-ary Tree.
- The first element of the array arr[] is the root node.
- Then, followed by a number N, which denotes the number of children of the previous node. Value zero denotes Null Node.
Examples:
Input: arr[] = { 10, 3, 20, 30, 40, 2, 40, 50, 0, 0, 0, 0 }
Below is the N-ary Tree of the above array level order traversal:

Output:
Below is the representation of the above output:

Input: arr[] = {1, 3, 2, 3, 4, 2, 5, 6, 0, 0, 2, 8, 9, 0}
Below is the N-ary Tree of the above array level order traversal:

Output:
Below is the representation of the above output:

Approach:
- Traverse the tree starting from root.
- While traversing pass depth of node as a parameter.
- Track depth by passing it as 0 for root and (1 + current level) for children.
Below is the implementation of the above approach:
CPP
// C++ program to implement node with
// it's depth value
#include <bits/stdc++.h>
using namespace std;
// Treenode class using template
template <typename T>
class TreeNode {
public:
// To store node value
T data;
// Pointer to TreeNode to store
// the child node
vector<TreeNode<T>*> children;
// Constructor to assign data
// to node
TreeNode(T data)
{
this->data = data;
}
// Destructors to delete a node
~TreeNode()
{
for (int i = 0;
i < children.size(); i++) {
delete children[i];
}
}
};
// Function to take input level wise
// i.e., in level order traversal
TreeNode<int>* takeInputLevelWise(int arr[])
{
int idx = 1;
// Input root
int rootData = arr[0];
// Initialize tree with a root node
TreeNode<int>* root
= new TreeNode<int>(rootData);
// Initialise queue for appending
// node as a child of parent in
// N-ary tree
queue<TreeNode<int>*> pendingNodes;
// Push the root node in queue
pendingNodes.push(root);
// While queue is not empty append
// child to the root
while (pendingNodes.size() != 0) {
// Take the first node
TreeNode<int>* front
= pendingNodes.front();
pendingNodes.pop();
// Input number of child
int numChild = arr[idx];
idx++;
for (int i = 0; i < numChild; i++) {
int childData = arr[idx];
idx++;
// Make child Node
TreeNode<int>* child
= new TreeNode<int>(childData);
// Append child node to
// it's parent
front->children.push_back(child);
pendingNodes.push(child);
}
}
return root;
}
// Function to print each node data
// in level order
void printLevelATNewLine(TreeNode<int>* root)
{
queue<TreeNode<int>*> q;
q.push(root);
q.push(NULL);
while (!q.empty()) {
TreeNode<int>* first = q.front();
q.pop();
if (first == NULL) {
if (q.empty()) {
break;
}
cout << endl;
q.push(NULL);
continue;
}
cout << first->data << " ";
for (int i = 0;
i < first->children.size(); i++) {
q.push(first->children[i]);
}
}
}
// Helper function to replace the
// node data with their level value
void helper(TreeNode<int>* root,
int depth)
{
// Replace the node data with
// it's depth
root->data = depth;
for (int i = 0;
i < root->children.size(); i++) {
helper(root->children[i], depth + 1);
}
}
// Function to replace with depth
void replaceWithDepthValue(TreeNode<int>* root)
{
helper(root, 0);
}
// Driver Code
int main()
{
// Given level order traversal in
// the array arr[]
int arr[] = { 1, 3, 2, 3, 4, 2, 5, 6, 0, 0, 2, 8, 9, 0};
// Initialise Tree
TreeNode<int>* root;
root = takeInputLevelWise(arr);
// Function call to replace with
// depth value
replaceWithDepthValue(root);
// Function call to print
// in level order
printLevelATNewLine(root);
return 0;
}
Java
// Java program to replace node with
// it's depth value
// Importing classes and interface
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.Queue;
class GFG {
// TreeNode class
static class TreeNode<T> {
// To store node value
T data;
// List of TreeNode to store
// the child nodes
ArrayList<TreeNode<T> > children;
// Constructor to assign data to node
TreeNode(T data)
{
this.data = data;
children = new ArrayList<TreeNode<T> >();
}
}
// Function to take input level wise
// i.e., in level order traversal
static TreeNode<Integer> takeInputLevelWise(int arr[])
{
int idx = 1;
// Input root
int rootData = arr[0];
// Initialize tree with a root node
TreeNode<Integer> root
= new TreeNode<Integer>(rootData);
// Initialize queue for appending
// node as a child of parent in
// N-ary tree
Queue<TreeNode<Integer> > pendingNodes
= new LinkedList<TreeNode<Integer> >();
// Push the root node in queue
pendingNodes.add(root);
// While queue is not empty append
// child to the node
while (pendingNodes.size() != 0) {
// Take the first node
TreeNode<Integer> front = pendingNodes.peek();
pendingNodes.poll();
// Input number of its child
int numChild = arr[idx];
idx++;
for (int i = 0; i < numChild; i++) {
int childData = arr[idx];
idx++;
// Make child Node
TreeNode<Integer> child
= new TreeNode<Integer>(childData);
// Append child node to
// it's parent
front.children.add(child);
pendingNodes.add(child);
}
}
return root;
}
// Function to print each node data
// in level order
static void printLevelATNewLine(TreeNode<Integer> root)
{
Queue<TreeNode<Integer> > q
= new LinkedList<TreeNode<Integer> >();
q.add(root);
q.add(null);
while (!q.isEmpty()) {
TreeNode<Integer> first = q.peek();
q.poll();
if (first == null) {
// If there is no more nodes
if (q.isEmpty()) {
break;
}
// All the nodes of current level are
// visited
System.out.println();
q.add(null);
continue;
}
System.out.print(first.data + " ");
// Append current node's child to queue
for (int i = 0; i < first.children.size();
i++) {
q.add(first.children.get(i));
}
}
}
// Helper function to replace the
// node data with their level value
static void helper(TreeNode<Integer> root, int depth)
{
// Replace the node data with
// it's depth
root.data = depth;
for (int i = 0; i < root.children.size(); i++) {
helper(root.children.get(i), depth + 1);
}
}
// Function to replace with depth
static void
replaceWithDepthValue(TreeNode<Integer> root)
{
helper(root, 0);
}
// Driver Code
public static void main(String[] args)
{
// Given level order traversal in
// the array arr[]
int arr[]
= { 10, 3, 20, 30, 40, 2, 40, 50, 0, 0, 0, 0 };
// Initialise Tree
TreeNode<Integer> root;
root = takeInputLevelWise(arr);
// Function call to replace with
// depth value
replaceWithDepthValue(root);
// Function call to print
// in level order
printLevelATNewLine(root);
}
}
// This code is contributed by jainlovely450
Python
# Python code for the above approach
from typing import List, Tuple
# TreeNode class
class TreeNode:
# To store node value
data: int
# List of TreeNode to store
# the child nodes
children: List['TreeNode']
# Constructor to assign data to node
def __init__(self, data: int):
self.data = data
self.children = []
# Function to take input level wise
# i.e., in level order traversal
def take_input_level_wise(arr: List[int]) -> TreeNode:
idx = 1
# Input root
root_data = arr[0]
# Initialize tree with a root node
root = TreeNode(root_data)
# Initialize queue for appending
# node as a child of parent in
# N-ary tree
pending_nodes = [root]
# While queue is not empty append
# child to the node
while pending_nodes:
# Take the first node
front = pending_nodes[0]
pending_nodes = pending_nodes[1:]
# Input number of its child
num_child = arr[idx]
idx += 1
for i in range(num_child):
child_data = arr[idx]
idx += 1
# Make child Node
child = TreeNode(child_data)
# Append child node to
# it's parent
front.children.append(child)
pending_nodes.append(child)
return root
# Function to print each node data
# in level order
def print_level_at_new_line(root: TreeNode):
q = [root]
q.append(None)
while q:
first = q[0]
q = q[1:]
if first is None:
# If there is no more nodes
if not q:
break
# All the nodes of current level are
# visited
print()
q.append(None)
continue
print(first.data, end=' ')
# Append current node's child to queue
for i in range(len(first.children)):
q.append(first.children[i])
# Helper function to replace the
# node data with their level value
def helper(root: TreeNode, depth: int):
# Replace the node data with
# it's depth
root.data = depth
for i in range(len(root.children)):
helper(root.children[i], depth + 1)
# Function to replace with depth
def replace_with_depth_value(root: TreeNode):
helper(root, 0)
# Driver Code
if __name__ == '__main__':
# Given level order traversal in
# the array arr[]
arr = [10, 3, 20, 30, 40, 2, 40, 50, 0, 0, 0, 0]
# Initialise Tree
root = take_input_level_wise(arr)
# Function call to replace with
# depth value
replace_with_depth_value(root)
# Print the tree in level order
print_level_at_new_line(root)
# This code is contributed by Potta Lokesh
C#
using System;
using System.Collections.Generic;
// Class to represent a node with data and its children in
// N-ary tree
class TreeNode<T> {
public T Data
{
get;
set;
}
public List<TreeNode<T> > Children
{
get;
set;
}
public TreeNode(T data)
{
this.Data = data;
this.Children = new List<TreeNode<T> >();
}
}
class GFG {
static void Main(string[] args)
{
// Input level order data
int[] arr
= { 10, 3, 20, 30, 40, 2, 40, 50, 0, 0, 0, 0 };
// Initialize Tree with root node
var root = TakeInputLevelWise(arr);
// Replace the node data with their depth value
ReplaceWithDepthValue(root, 0);
// Print level order
PrintLevelAtNewLine(root);
}
// Function to take input level wise
static TreeNode<int> TakeInputLevelWise(int[] arr)
{
int idx = 1;
// Input root data
int rootData = arr[0];
var root = new TreeNode<int>(rootData);
// Initialise queue for appending node as a child of
// parent
var pendingNodes = new Queue<TreeNode<int> >();
// Push the root node in queue
pendingNodes.Enqueue(root);
// While queue is not empty append child to the root
while (pendingNodes.Count != 0) {
// Take the first node
var front = pendingNodes.Dequeue();
// Input number of children
int numChild = arr[idx];
idx++;
for (int i = 0; i < numChild; i++) {
int childData = arr[idx];
idx++;
// Make child node
var child = new TreeNode<int>(childData);
// Append child node to its parent
front.Children.Add(child);
pendingNodes.Enqueue(child);
}
}
return root;
}
// Function to print level order
static void PrintLevelAtNewLine(TreeNode<int> root)
{
var q = new Queue<TreeNode<int> >();
q.Enqueue(root);
q.Enqueue(null);
while (q.Count != 0) {
var first = q.Dequeue();
if (first == null) {
if (q.Count == 0) {
break;
}
Console.WriteLine();
q.Enqueue(null);
continue;
}
Console.Write(first.Data + " ");
foreach(var child in first.Children)
{
q.Enqueue(child);
}
}
}
// Function to replace node data with their depth value
static void ReplaceWithDepthValue(TreeNode<int> root,
int depth)
{
root.Data = depth;
foreach(var child in root.Children)
{
ReplaceWithDepthValue(child, depth + 1);
}
}
}
//This Code is Contributed by chinmaya121221
JavaScript
// JavaScript program to replace node with it's depth value
// TreeNode class
class TreeNode {
constructor(data) {
// To store node value
this.data = data;
// List of TreeNode to store the child nodes
this.children = [];
}
}
// Function to take input level wise i.e., in level order traversal
function takeInputLevelWise(arr) {
let idx = 1;
// Input root
let rootData = arr[0];
// Initialize tree with a root node
const root = new TreeNode(rootData);
// Initialize queue for appending node as a child of parent in N-ary tree
const pendingNodes = [];
// Push the root node in queue
pendingNodes.push(root);
// While queue is not empty append child to the node
while (pendingNodes.length !== 0) {
// Take the first node
const front = pendingNodes.shift();
// Input number of its child
const numChild = arr[idx];
idx++;
for (let i = 0; i < numChild; i++) {
const childData = arr[idx];
idx++;
// Make child Node
const child = new TreeNode(childData);
// Append child node to it's parent
front.children.push(child);
pendingNodes.push(child);
}
}
return root;
}
// Function to print each node data in level order
function printLevelATNewLine(root) {
const q = [];
q.push(root);
q.push(null);
while (q.length !== 0) {
const first = q.shift();
if (first === null) {
// If there is no more nodes
if (q.length === 0) {
break;
}
// All the nodes of current level are visited
console.log("<br>");
q.push(null);
continue;
}
console.log(first.data + " ");
// Append current node's child to queue
for (let i = 0; i < first.children.length; i++) {
q.push(first.children[i]);
}
}
}
// Helper function to replace the node data with their level value
function helper(root, depth) {
// Replace the node data with it's depth
root.data = depth;
for (let i = 0; i < root.children.length; i++) {
helper(root.children[i], depth + 1);
}
}
// Function to replace with depth
function replaceWithDepthValue(root) {
helper(root, 0);
}
// Given level order traversal in the array arr[]
const arr = [10, 3, 20, 30, 40, 2, 40, 50, 0, 0, 0, 0];
// Initialise Tree
let root = takeInputLevelWise(arr);
// Function call to replace with depth value
replaceWithDepthValue(root);
// Function call to print in level order
printLevelATNewLine(root);
// This code is contributed by sankar.
Time Complexity: O(N), where N is the number of nodes in Tree.
Auxiliary Space: O(N), where N is the number of nodes in Tree.
Another Approach: We can also replace the node's value with its depth while creating the tree. We are traversing the array level wise which means that nodes currently present in the queue are of the same depth. As we append its child nodes to the queue, they will be present in the next level. We can initialize a variable as current depth equal to 1 and when we create child node we can assign its value to current depth level. After traversing all the nodes present in the current level we will increment current depth level by 1.
C++
// C++ program to implement node with
// it's depth value
#include <bits/stdc++.h>
using namespace std;
// Treenode class using template
template <typename T> class TreeNode {
public:
// To store node value
T data;
// Pointer to TreeNode to store
// the child node
vector<TreeNode<T>*> children;
// Constructor to assign data
// to node
TreeNode(T data) { this->data = data; }
// Destructors to delete a node
~TreeNode()
{
for (int i = 0; i < children.size(); i++) {
delete children[i];
}
}
};
// Function to take input level wise
// i.e., in level order traversal
TreeNode<int>* takeInputLevelWise(int arr[])
{
int idx = 1;
int depthLevel = 1;
// Initialize tree with a root node
// with depth 0
TreeNode<int>* root = new TreeNode<int>(0);
// Initialise queue for appending
// node as a child of parent in
// N-ary tree
queue<TreeNode<int>*> pendingNodes;
// Push the root node in queue
pendingNodes.push(root);
// While queue is not empty append
// child to the node
while (pendingNodes.size() != 0) {
// Number of nodes present in the current level
int size = pendingNodes.size();
while (size > 0) {
// Take the first node
TreeNode<int>* front = pendingNodes.front();
pendingNodes.pop();
// Input number of its child
int numChild = arr[idx];
idx++;
for (int i = 0; i < numChild; i++) {
idx++;
// Make child Node and assign its data
// value equal to depthLevel
TreeNode<int>* child
= new TreeNode<int>(depthLevel);
// Append child node to
// it's parent
front->children.push_back(child);
pendingNodes.push(child);
}
size--;
}
// Increment depth level
depthLevel++;
}
return root;
}
// Function to print each node data
// in level order
void printLevelATNewLine(TreeNode<int>* root)
{
queue<TreeNode<int>*> q;
q.push(root);
q.push(NULL);
while (!q.empty()) {
TreeNode<int>* first = q.front();
q.pop();
if (first == NULL) {
// If there is no more nodes to visit
if (q.empty()) {
break;
}
// All the nodes of current level are visited
cout << endl;
q.push(NULL);
continue;
}
cout << first->data << " ";
// Append current node's child to queue
for (int i = 0; i < first->children.size(); i++) {
q.push(first->children[i]);
}
}
}
// Driver Code
int main()
{
// Given level order traversal in
// the array arr[]
int arr[]
= { 10, 3, 20, 30, 40, 2, 40, 50, 0, 0, 0, 0 };
// Initialise Tree
TreeNode<int>* root;
root = takeInputLevelWise(arr);
// Function call to print
// in level order
printLevelATNewLine(root);
return 0;
}
// This code is contributed by jainlovely450
Java
// Java program to implement node with
// it's depth value
// Importing classes and interface
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.Queue;
public class GFG {
// TreeNode class
static class TreeNode<T> {
// To store node value
T data;
// List of TreeNode to store
// the child nodes
ArrayList<TreeNode<T> > children;
// Constructor to assign data to node
TreeNode(T data)
{
this.data = data;
children = new ArrayList<TreeNode<T> >();
}
}
// Function to take input level wise
// i.e., in level order traversal and
// assign value of node equal to its depth
static TreeNode<Integer> takeInputLevelWise(int arr[])
{
int idx = 1;
int depthLevel = 1;
// Initialize tree with a root node
// with depth 0
TreeNode<Integer> root = new TreeNode<Integer>(0);
// Initialize queue for appending
// node as a child of parent in
// N-ary tree
Queue<TreeNode<Integer> > pendingNodes
= new LinkedList<TreeNode<Integer> >();
// Push the root node in queue
pendingNodes.add(root);
// While queue is not empty append
// child to the node
while (!pendingNodes.isEmpty()) {
// Number of nodes present in the current level
int size = pendingNodes.size();
while (size > 0) {
TreeNode<Integer> front
= pendingNodes.peek();
pendingNodes.poll();
// Input number of child
int numChild = arr[idx];
idx++;
for (int i = 0; i < numChild; i++) {
idx++;
// Make child Node and assign its data
// value equal to depthLevel
TreeNode<Integer> child
= new TreeNode<Integer>(depthLevel);
// Append child node to
// it's parent
front.children.add(child);
pendingNodes.add(child);
}
size--;
}
// Increment depth level
depthLevel++;
}
return root;
}
// Function to print each node data
// in level order
static void printLevelATNewLine(TreeNode<Integer> root)
{
Queue<TreeNode<Integer> > q
= new LinkedList<TreeNode<Integer> >();
q.add(root);
q.add(null);
while (!q.isEmpty()) {
TreeNode<Integer> first = q.peek();
q.poll();
if (first == null) {
// If there is no more nodes to visit
if (q.isEmpty()) {
break;
}
// All the nodes of current level are
// visited
System.out.println();
q.add(null);
continue;
}
System.out.print(first.data + " ");
// Append current node's child to queue
for (int i = 0; i < first.children.size();
i++) {
q.add(first.children.get(i));
}
}
}
// Driver Code
public static void main(String[] args)
{
// Given level order traversal in
// the array arr[]
int arr[]
= { 10, 3, 20, 30, 40, 2, 40, 50, 0, 0, 0, 0 };
// Initialize Tree
TreeNode<Integer> root;
root = takeInputLevelWise(arr);
// Function call to print
// in level order
printLevelATNewLine(root);
}
}
// This code is contributed by jainlovely450
Python
# Python code
# TreeNode class
class TreeNode:
# To store node value
def __init__(self, data):
self.data = data
# List of TreeNode to store
# the child nodes
self.children = []
# Function to take input level wise
# i.e., in level order traversal and
# assign value of node equal to its depth
def takeInputLevelWise(arr):
idx = 1
depthLevel = 1
# Initialize tree with a root node
# with depth 0
root = TreeNode(0)
# Initialize queue for appending
# node as a child of parent in
# N-ary tree
pendingNodes = []
pendingNodes.append(root)
# While queue is not empty append
# child to the node
while pendingNodes:
# Number of nodes present in the current level
size = len(pendingNodes)
while size > 0:
front = pendingNodes[0]
pendingNodes.pop(0)
# Input number of child
numChild = arr[idx]
idx += 1
for i in range(numChild):
idx += 1
# Make child Node and assign its data
# value equal to depthLevel
child = TreeNode(depthLevel)
# Append child node to
# it's parent
front.children.append(child)
pendingNodes.append(child)
size -= 1
# Increment depth level
depthLevel += 1
return root
# Function to print each node data
# in level order
def printLevelATNewLine(root):
q = []
q.append(root)
q.append(None)
while q:
first = q[0]
q.pop(0)
if first is None:
# If there is no more nodes to visit
if not q:
break
# All the nodes of current level are
# visited
print()
q.append(None)
continue
print(first.data, end=" ")
# Append current node's child to queue
for i in range(len(first.children)):
q.append(first.children[i])
# Driver Code
if __name__ == '__main__':
# Given level order traversal in
# the array arr[]
arr = [10, 3, 20, 30, 40, 2, 40, 50, 0, 0, 0, 0]
# Initialize Tree
root = takeInputLevelWise(arr)
# Function call to print
# in level order
printLevelATNewLine(root)
C#
// C# program to implement node with it's depth value
using System;
using System.Collections.Generic;
public class GFG {
// TreeNode class
class TreeNode<T> {
// To store node value
public T data;
// List of TreeNode to store
// the child nodes
public List<TreeNode<T> > children;
// Constructor to assign data to node
public TreeNode(T data)
{
this.data = data;
children = new List<TreeNode<T> >();
}
}
// Function to take input level wise i.e., in level
// order traversal and assign value of node equal to its
// depth
static TreeNode<int> takeInputLevelWise(int[] arr)
{
int idx = 1;
int depthLevel = 1;
// Initialize tree with a root node with depth 0
TreeNode<int> root = new TreeNode<int>(0);
// Initialize queue for appending node as a child of
// parent in N-ary tree
Queue<TreeNode<int> > pendingNodes
= new Queue<TreeNode<int> >();
// Push the root node in queue
pendingNodes.Enqueue(root);
// While queue is not empty append child to the node
while (pendingNodes.Count != 0) {
// Number of nodes present in the current level
int size = pendingNodes.Count;
while (size > 0) {
TreeNode<int> front = pendingNodes.Peek();
pendingNodes.Dequeue();
// Input number of child
int numChild = arr[idx];
idx++;
for (int i = 0; i < numChild; i++) {
idx++;
// Make child Node and assign its data
// value equal to depthLevel
TreeNode<int> child
= new TreeNode<int>(depthLevel);
// Append child node to it's parent
front.children.Add(child);
pendingNodes.Enqueue(child);
}
size--;
}
// Increment depth level
depthLevel++;
}
return root;
}
// Function to print each node data in level order
static void printLevelATNewLine(TreeNode<int> root)
{
Queue<TreeNode<int> > q
= new Queue<TreeNode<int> >();
q.Enqueue(root);
q.Enqueue(null);
while (q.Count != 0) {
TreeNode<int> first = q.Peek();
q.Dequeue();
if (first == null) {
// If there is no more nodes to visit
if (q.Count == 0) {
break;
}
// All the nodes of current level are
// visited
Console.WriteLine();
q.Enqueue(null);
continue;
}
Console.Write(first.data + " ");
// Append current node's child to queue
for (int i = 0; i < first.children.Count; i++) {
q.Enqueue(first.children[i]);
}
}
}
static public void Main()
{
// Code
// Given level order traversal in the array arr[]
int[] arr
= { 10, 3, 20, 30, 40, 2, 40, 50, 0, 0, 0, 0 };
// Initialize Tree
TreeNode<int> root;
root = takeInputLevelWise(arr);
// Function call to print in level order
printLevelATNewLine(root);
}
}
// This code is contributed by karthik.
JavaScript
// JavaScript program to implement node with
// it's depth value
// TreeNode class
class TreeNode {
// To store node value
constructor(data) {
this.data = data;
// List of TreeNode to store
// the child nodes
this.children = [];
}
}
// Function to take input level wise
// i.e., in level order traversal and
// assign value of node equal to its depth
function takeInputLevelWise(arr) {
let idx = 1;
let depthLevel = 1;
// Initialize tree with a root node
// with depth 0
const root = new TreeNode(0);
// Initialize queue for appending
// node as a child of parent in
// N-ary tree
const pendingNodes = [];
// Push the root node in queue
pendingNodes.push(root);
// While queue is not empty append
// child to the node
while (pendingNodes.length !== 0) {
// Number of nodes present in the current level
let size = pendingNodes.length;
while (size > 0) {
const front = pendingNodes.shift();
// Input number of child
const numChild = arr[idx];
idx++;
for (let i = 0; i < numChild; i++) {
idx++;
// Make child Node and assign its data
// value equal to depthLevel
const child = new TreeNode(depthLevel);
// Append child node to
// it's parent
front.children.push(child);
pendingNodes.push(child);
}
size--;
}
// Increment depth level
depthLevel++;
}
return root;
}
// Function to print each node data
// in level order
function printLevelATNewLine(root) {
const q = [];
q.push(root);
q.push(null);
while (q.length !== 0) {
const first = q.shift();
if (first === null) {
// If there is no more nodes to visit
if (q.length === 0) {
break;
}
// All the nodes of current level are
// visited
console.log("<br>");
q.push(null);
continue;
}
console.log(first.data + " ");
// Append current node's child to queue
for (let i = 0; i < first.children.length; i++) {
q.push(first.children[i]);
}
}
console.log("<br>")
}
// Given level order traversal in
// the array arr[]
const arr = [10, 3, 20, 30, 40, 2, 40, 50, 0, 0, 0, 0];
// Initialize Tree
const root = takeInputLevelWise(arr);
// Function call to print
// in level order
printLevelATNewLine(root);
// This code is contributed by karthik.
Time Complexity: O(N), where N is the number of nodes in Tree.
Auxiliary Space: O(N), where N is the number of nodes in Tree.
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