Next Larger element in n-ary tree
Last Updated :
21 Apr, 2025
Given a generic tree and a integer x. Find and return the node with next larger element in the tree i.e. find a node just greater than x. Return NULL if no node is present with value greater than x.
For example, in the given tree, x = 10, just greater node value is 12
The idea is maintain a node pointer res, which will contain the final resultant node.
Traverse the tree and check if root data is greater than x. If so, then compare the root data with res data.
If root data is greater than n and less than res data update res.
Implementation:
C++
// CPP program to find next larger element
// in an n-ary tree.
#include <bits/stdc++.h>
using namespace std;
// Structure of a node of an n-ary tree
struct Node {
int key;
vector<Node*> child;
};
// Utility function to create a new tree node
Node* newNode(int key)
{
Node* temp = new Node;
temp->key = key;
return temp;
}
void nextLargerElementUtil(Node* root, int x, Node** res)
{
if (root == NULL)
return;
// if root is less than res but greater than
// x update res
if (root->key > x)
if (!(*res) || (*res)->key > root->key)
*res = root;
// Number of children of root
int numChildren = root->child.size();
// Recur calling for every child
for (int i = 0; i < numChildren; i++)
nextLargerElementUtil(root->child[i], x, res);
return;
}
// Function to find next Greater element of x in tree
Node* nextLargerElement(Node* root, int x)
{
// resultant node
Node* res = NULL;
// calling helper function
nextLargerElementUtil(root, x, &res);
return res;
}
// Driver program
int main()
{
/* Let us create below tree
* 5
* / | \
* 1 2 3
* / / \ \
* 15 4 5 6
*/
Node* root = newNode(5);
(root->child).push_back(newNode(1));
(root->child).push_back(newNode(2));
(root->child).push_back(newNode(3));
(root->child[0]->child).push_back(newNode(15));
(root->child[1]->child).push_back(newNode(4));
(root->child[1]->child).push_back(newNode(5));
(root->child[2]->child).push_back(newNode(6));
int x = 5;
cout << "Next larger element of " << x << " is ";
cout << nextLargerElement(root, x)->key << endl;
return 0;
}
Java
// Java program to find next larger element
// in an n-ary tree.
import java.util.*;
class GFG
{
// Structure of a node of an n-ary tree
static class Node
{
int key;
Vector<Node> child;
};
static Node res;
// Utility function to create a new tree node
static Node newNode(int key)
{
Node temp = new Node();
temp.key = key;
temp.child = new Vector<>();
return temp;
}
static void nextLargerElementUtil(Node root, int x)
{
if (root == null)
return;
// if root is less than res but
// greater than x, update res
if (root.key > x)
if ((res == null || (res).key > root.key))
res = root;
// Number of children of root
int numChildren = root.child.size();
// Recur calling for every child
for (int i = 0; i < numChildren; i++)
nextLargerElementUtil(root.child.get(i), x);
return;
}
// Function to find next Greater element
// of x in tree
static Node nextLargerElement(Node root, int x)
{
// resultant node
res = null;
// calling helper function
nextLargerElementUtil(root, x);
return res;
}
// Driver Code
public static void main(String[] args)
{
/* Let us create below tree
* 5
* / | \
* 1 2 3
* / / \ \
* 15 4 5 6
*/
Node root = newNode(5);
(root.child).add(newNode(1));
(root.child).add(newNode(2));
(root.child).add(newNode(3));
(root.child.get(0).child).add(newNode(15));
(root.child.get(1).child).add(newNode(4));
(root.child.get(1).child).add(newNode(5));
(root.child.get(2).child).add(newNode(6));
int x = 5;
System.out.print("Next larger element of " +
x + " is ");
System.out.print(nextLargerElement(root, x).key + "\n");
}
}
// This code is contributed by 29AjayKumar
Python
# Python program to find next larger element
# in an n-ary tree.
class Node:
# Structure of a node of an n-ary tree
def __init__(self):
self.key = 0
self.child = []
# Utility function to create a new tree node
def newNode(key):
temp = Node()
temp.key = key
temp.child = []
return temp
res = None;
def nextLargerElementUtil(root,x):
global res
if (root == None):
return;
# if root is less than res but
# greater than x, update res
if (root.key > x):
if ((res == None or (res).key > root.key)):
res = root;
# Number of children of root
numChildren = len(root.child)
# Recur calling for every child
for i in range(numChildren):
nextLargerElementUtil(root.child[i], x)
return
# Function to find next Greater element
# of x in tree
def nextLargerElement(root,x):
# resultant node
global res
res=None
# Calling helper function
nextLargerElementUtil(root, x)
return res
# Driver code
root = newNode(5)
(root.child).append(newNode(1))
(root.child).append(newNode(2))
(root.child).append(newNode(3))
(root.child[0].child).append(newNode(15))
(root.child[1].child).append(newNode(4))
(root.child[1].child).append(newNode(5))
(root.child[2].child).append(newNode(6))
x = 5
print("Next larger element of " , x , " is ",end='')
print(nextLargerElement(root, x).key)
# This code is contributed by rag2127.
C#
// C# program to find next larger element
// in an n-ary tree.
using System;
using System.Collections.Generic;
class GFG
{
// Structure of a node of an n-ary tree
class Node
{
public int key;
public List<Node> child;
};
static Node res;
// Utility function to create a new tree node
static Node newNode(int key)
{
Node temp = new Node();
temp.key = key;
temp.child = new List<Node>();
return temp;
}
static void nextLargerElementUtil(Node root,
int x)
{
if (root == null)
return;
// if root is less than res but
// greater than x, update res
if (root.key > x)
if ((res == null ||
(res).key > root.key))
res = root;
// Number of children of root
int numChildren = root.child.Count;
// Recur calling for every child
for (int i = 0; i < numChildren; i++)
nextLargerElementUtil(root.child[i], x);
return;
}
// Function to find next Greater element
// of x in tree
static Node nextLargerElement(Node root,
int x)
{
// resultant node
res = null;
// calling helper function
nextLargerElementUtil(root, x);
return res;
}
// Driver Code
public static void Main(String[] args)
{
/* Let us create below tree
* 5
* / | \
* 1 2 3
* / / \ \
* 15 4 5 6
*/
Node root = newNode(5);
(root.child).Add(newNode(1));
(root.child).Add(newNode(2));
(root.child).Add(newNode(3));
(root.child[0].child).Add(newNode(15));
(root.child[1].child).Add(newNode(4));
(root.child[1].child).Add(newNode(5));
(root.child[2].child).Add(newNode(6));
int x = 5;
Console.Write("Next larger element of " +
x + " is ");
Console.Write(nextLargerElement(root, x).key + "\n");
}
}
// This code is contributed by PrinciRaj1992
JavaScript
// JavaScript program to find next larger element
// in an n-ary tree.
// Structure of a node of an n-ary tree
class Node
{
constructor()
{
this.key = 0;
this.child = [];
}
};
var res = null;
// Utility function to create a new tree node
function newNode(key)
{
var temp = new Node();
temp.key = key;
temp.child = [];
return temp;
}
function nextLargerElementUtil(root, x)
{
if (root == null)
return;
// if root is less than res but
// greater than x, update res
if (root.key > x)
if ((res == null ||
(res).key > root.key))
res = root;
// Number of children of root
var numChildren = root.child.length;
// Recur calling for every child
for (var i = 0; i < numChildren; i++)
nextLargerElementUtil(root.child[i], x);
return;
}
// Function to find next Greater element
// of x in tree
function nextLargerElement(root, x)
{
// resultant node
res = null;
// calling helper function
nextLargerElementUtil(root, x);
return res;
}
// Driver Code
/* Let us create below tree
* 5
* / | \
* 1 2 3
* / / \ \
* 15 4 5 6
*/
var root = newNode(5);
(root.child).push(newNode(1));
(root.child).push(newNode(2));
(root.child).push(newNode(3));
(root.child[0].child).push(newNode(15));
(root.child[1].child).push(newNode(4));
(root.child[1].child).push(newNode(5));
(root.child[2].child).push(newNode(6));
var x = 5;
console.log("Next larger element of " +
x + " is ");
console.log(nextLargerElement(root, x).key + "<br>");
OutputNext larger element of 5 is 6
Time complexity :- O(N)
Space complexity :- O(H)
Example no2:
Algorithmic steps:
Traverse the tree in post-order and store the nodes in a stack.
Create an empty hash map to store the next larger element for each node.
For each node in the stack, pop it from the stack and find the next larger element for it by checking the elements on the top of the stack. If an element on the top of the stack is greater than the current node, it is the next larger element for the current node. Keep popping elements from the stack until the top of the stack is less than or equal to the current node.
Add the next larger element for the current node to the hash map.
Repeat steps 3 and 4 until the stack is empty.
Return the next larger element for the target node by looking it up in the hash map.
Note: This algorithm assumes that the tree is a binary search tree, where the value of each node is greater than the values of its left child and less than the values of its right child. If the tree is not a binary search tree, the above algorithm may not give correct result
Program: Implementing by Postorder traversing tree:
C++
#include <iostream>
#include <stack>
#include <unordered_map>
struct TreeNode {
int val;
vector<TreeNode*> children;
TreeNode(int x) : val(x) {}
};
void postOrder(TreeNode *root, stack<int> &nodes) {
if (!root) return;
for (int i = 0; i < root->children.size(); i++) {
postOrder(root->children[i], nodes);
}
nodes.push(root->val);
}
unordered_map<int, int> findNextLarger(TreeNode *root) {
stack<int> nodes;
unordered_map<int, int> nextLarger;
postOrder(root, nodes);
while (!nodes.empty()) {
int current = nodes.top();
nodes.pop();
while (!nodes.empty() && nodes.top() <= current) {
nodes.pop();
}
if (!nodes.empty()) {
nextLarger[current] = nodes.top();
} else {
nextLarger[current] = -1;
}
}
return nextLarger;
}
int main() {
TreeNode *root = new TreeNode(8);
root->children.push_back(new TreeNode(3));
root->children.push_back(new TreeNode(10));
root->children[0]->children.push_back(new TreeNode(1));
root->children[0]->children.push_back(new TreeNode(6));
root->children[0]->children[1]->children.push_back(new TreeNode(4));
root->children[0]->children[1]->children.push_back(new TreeNode(7));
root->children[1]->children.push_back(new TreeNode(14));
int target = 4;
unordered_map<int, int> nextLarger = findNextLarger(root);
cout << "The next larger element for " << target << " is: " << nextLarger[target] << endl;
return 0;
}
Java
import java.util.*;
class TreeNode {
int val;
List<TreeNode> children;
TreeNode(int x) {
val = x;
children = new ArrayList<>();
}
}
public class Main {
static void postOrder(TreeNode root, Stack<Integer> nodes) {
if (root == null)
return;
for (TreeNode child : root.children) {
postOrder(child, nodes);
}
nodes.push(root.val);
}
static Map<Integer, Integer> findNextLarger(TreeNode root) {
Stack<Integer> nodes = new Stack<>();
Map<Integer, Integer> nextLarger = new HashMap<>();
postOrder(root, nodes);
Stack<Integer> stack = new Stack<>();
for (int i = nodes.size() - 1; i >= 0; i--) {
while (!stack.isEmpty() && stack.peek() <= nodes.get(i)) {
stack.pop();
}
nextLarger.put(nodes.get(i), stack.isEmpty() ? -1 : stack.peek());
stack.push(nodes.get(i));
}
return nextLarger;
}
public static void main(String[] args) {
TreeNode root = new TreeNode(8);
root.children = new ArrayList<>();
root.children.add(new TreeNode(3));
root.children.add(new TreeNode(10));
root.children.get(0).children = new ArrayList<>();
root.children.get(0).children.add(new TreeNode(1));
root.children.get(0).children.add(new TreeNode(6));
root.children.get(0).children.get(1).children = new ArrayList<>();
root.children.get(0).children.get(1).children.add(new TreeNode(4));
root.children.get(0).children.get(1).children.add(new TreeNode(7));
root.children.get(1).children = new ArrayList<>();
root.children.get(1).children.add(new TreeNode(14));
int target = 4;
Map<Integer, Integer> nextLarger = findNextLarger(root);
Integer nextLargerValue = nextLarger.get(target);
System.out.println("The next larger element for " + target + " is: " + (nextLargerValue != null ? nextLargerValue : -1));
}
}
Python
class Node:
# Structure of a node of an n-ary tree
def __init__(self):
self.vcal = 0
self.children = []
# Utility function to create a new tree node
def newNode(val):
temp = Node()
temp.val = val
temp.children = []
return temp
def postOrder(root, nodes):
if not root:
return
for child in root.children:
postOrder(child, nodes)
nodes.append(root.val)
def findNextLarger(root):
nodes = []
nextLarger = {}
postOrder(root, nodes)
stack = []
for num in nodes[::-1]:
while stack and stack[-1] <= num:
stack.pop()
nextLarger[num] = stack[-1] if stack else -1
stack.append(num)
return nextLarger
root = newNode(8)
root.children.append(newNode(3))
root.children.append(newNode(10))
root.children[0].children.append(newNode(1))
root.children[0].children.append(newNode(6))
root.children[0].children[1].children.append(newNode(4))
root.children[0].children[1].children.append(newNode(7))
root.children[1].children.append(newNode(14))
target = 4
nextLarger = findNextLarger(root)
print(f"The next larger element for {target} is: {nextLarger[target]}")
C#
using System;
using System.Collections.Generic;
class Node {
// Structure of a node of an n-ary tree
public int val;
public List<Node> children;
public Node()
{
val = 0;
children = new List<Node>();
}
}
public class MainClass {
// Utility function to create a new tree node
static Node NewNode(int val)
{
Node temp = new Node();
temp.val = val;
temp.children = new List<Node>();
return temp;
}
// Function to perform post-order traversal and store
// nodes in a list
static void PostOrder(Node root, List<int> nodes)
{
if (root == null)
return;
// Recursively perform post-order traversal for each
// child node
foreach(Node child in root.children)
{
PostOrder(child, nodes);
}
// Add the current node value to the list after
// processing all its children
nodes.Add(root.val);
}
// Function to find the next larger element for each
// node in the tree
static Dictionary<int, int> FindNextLarger(Node root)
{
List<int> nodes = new List<int>();
Dictionary<int, int> nextLarger
= new Dictionary<int, int>();
PostOrder(root, nodes);
Stack<int> stack = new Stack<int>();
for (int i = nodes.Count - 1; i >= 0; i--) {
// Keep popping elements from the end of the
// list until we find the next larger element
while (stack.Count > 0
&& stack.Peek() <= nodes[i]) {
stack.Pop();
}
// If a next larger element is found, store it
// in the dictionary
if (stack.Count > 0) {
nextLarger[nodes[i]] = stack.Peek();
}
// If no next larger element is found, set the
// value to -1
else {
nextLarger[nodes[i]] = -1;
}
stack.Push(nodes[i]);
}
return nextLarger;
}
public static void Main()
{
Node root = NewNode(8);
root.children.Add(NewNode(3));
root.children.Add(NewNode(10));
root.children[0].children.Add(NewNode(1));
root.children[0].children.Add(NewNode(6));
root.children[0].children[1].children.Add(
NewNode(4));
root.children[0].children[1].children.Add(
NewNode(7));
root.children[1].children.Add(NewNode(14));
int target = 4;
Dictionary<int, int> nextLarger
= FindNextLarger(root);
int nextLargerValue;
if (nextLarger.TryGetValue(target,
out nextLargerValue)) {
Console.WriteLine("The next larger element for "
+ target
+ " is: " + nextLargerValue);
}
else {
Console.WriteLine("The next larger element for "
+ target + " is: -1");
}
}
}
JavaScript
class TreeNode {
constructor(x) {
this.val = x;
this.children = [];
}
}
function postOrder(root, nodes) {
if (!root) return;
for (const child of root.children) {
postOrder(child, nodes);
}
nodes.push(root.val);
}
function findNextLarger(root) {
const nodes = [];
const nextLarger = new Map();
postOrder(root, nodes);
const stack = [];
for (let i = nodes.length - 1; i >= 0; i--) {
while (stack.length > 0 && stack[stack.length - 1] <= nodes[i]) {
stack.pop();
}
nextLarger.set(nodes[i], stack.length > 0 ? stack[stack.length - 1] : -1);
stack.push(nodes[i]);
}
return nextLarger;
}
const root = new TreeNode(8);
root.children.push(new TreeNode(3));
root.children.push(new TreeNode(10));
root.children[0].children.push(new TreeNode(1));
root.children[0].children.push(new TreeNode(6));
root.children[0].children[1].children.push(new TreeNode(4));
root.children[0].children[1].children.push(new TreeNode(7));
root.children[1].children.push(new TreeNode(14));
const target = 4;
const nextLarger = findNextLarger(root);
const nextLargerValue = nextLarger.get(target);
console.log(`The next larger element for ${target} is: ${nextLargerValue !== undefined ? nextLargerValue : -1}`);
The next larger element for 4 is 7
Time and Space complexities are:
The time complexity of this algorithm is O(n), where n is the number of nodes in the n-ary tree. The reason for this is that we traverse each node in the tree once, and for each node, we perform a constant amount of work to find its next larger element.
The auxiliary space of this algorithm is O(n), where n is the number of nodes in the n-ary tree. The reason for this is that we use a stack to store the nodes in post-order and a hash map to store the next larger element for each node. The size of the stack and the hash map is proportional to the number of nodes in the tree, so their combined space complexity is O(n).
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