Open In App

Next Larger element in n-ary tree

Last Updated : 27 May, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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>");

Output
Next 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).

 



Previous Article
Next Article

Similar Reads

Maximum Difference between Two Elements such that Larger Element Appears after the Smaller Element
Given an array arr[] of integers, find out the maximum difference between any two elements such that larger element appears after the smaller number. Examples : Input : arr = {2, 3, 10, 6, 4, 8, 1}Output : 8Explanation : The maximum difference is between 10 and 2. Input : arr = {7, 9, 5, 6, 3, 2}Output : 2Explanation : The maximum difference is bet
15+ min read
Reduce an array to a single element by repeatedly removing larger element from a pair with absolute difference at most K
Given an array arr[] consisting of N integers and a positive integer K, the task is to check if the given array can be reduced to a single element by repeatedly removing the larger of the two elements present in a pair whose absolute difference is at most K. If the array can be reduced to a single element, then print "Yes". Otherwise, print "No". E
11 min read
Remaining array element after repeated removal of last element and subtraction of each element from next adjacent element
Given an array arr[] consisting of N integers, the task is to find the remaining array element after subtracting each element from its next adjacent element and removing the last array element repeatedly. Examples: Input: arr[] = {3, 4, 2, 1}Output: 4Explanation:Operation 1: The array arr[] modifies to {4 - 3, 2 - 4, 1 - 2} = {1, -2, -1}.Operation
8 min read
Build a segment tree for N-ary rooted tree
Prerequisite: Segment tree and depth first search.In this article, an approach to convert an N-ary rooted tree( a tree with more than 2 children) into a segment tree is discussed which is used to perform a range update queries. Why do we need a segment tree when we already have an n-ary rooted tree? Many times, a situation occurs where the same ope
15+ min read
Check if the given n-ary tree is a binary tree
Given an n-ary tree, the task is to check whether the given tree is binary or not. Examples: Input: A / \ B C / \ \ D E F Output: Yes Input: A / | \ B C D \ F Output: No Approach: Every node in a binary tree can have at most 2 children. So, for every node of the given tree, count the number of children and if for any node the count exceeds 2 then p
6 min read
Remove all leaf nodes from a Generic Tree or N-ary Tree
Given a Generic tree, the task is to delete the leaf nodes from the tree. Examples: Input: 5 / / \ \ 1 2 3 8 / / \ \ 15 4 5 6 Output: 5 : 1 2 3 1 : 2 : 3 : Explanation: Deleted leafs are: 8, 15, 4, 5, 6 Input: 8 / | \ 9 7 2 / | \ | / / | \ \ 4 5 6 10 11 1 2 2 3 Output: 8: 9 7 2 9: 7: 2: Approach: Follow the steps given below to solve the problem Co
9 min read
Count of nodes in given N-ary tree such that their subtree is a Binary Tree
Given an N-ary tree root, the task is to find the count of nodes such that their subtree is a binary tree. Example: Input: Tree in the image below Output: 11Explanation: The nodes such that there subtree is a binary tree are {2, 8, 10, 6, 7, 3, 1, 9, 5, 11, 12}. Input: Tree in the image below Output: 9 Approach: The given problem can be solved by u
11 min read
Tree of Space - Locking and Unlocking N-Ary Tree
Given a world map in the form of Generic M-ary Tree consisting of N nodes and an array queries[], the task is to implement the functions Lock, Unlock and Upgrade for the given tree. For each query in queries[], the functions return true when the operation is performed successfully, otherwise it returns false. The functions are defined as: X: Name o
10 min read
Immediate Smaller element in an N-ary Tree
Given an element x, task is to find the value of its immediate smaller element. Example : Input : x = 30 (for above tree) Output : Immediate smaller element is 25 Explanation : Elements 2, 15, 20 and 25 are smaller than x i.e, 30, but 25 is the immediate smaller element and hence the answer. Approach : Let res be the resultant node.Initialize the r
7 min read
Find the cousins of a given element in an N-ary tree
Given an N-array tree root and an integer K, the task is to print all the cousins of node K. Note: Two nodes are considered to be cousins if they have the same depth (are on the same level) and have different parents. Examples: Consider the below tree: Input: K = 39Output: 88 98 61 74 17 72 19 Input: K = 17Output: 88 98 61 74 39 Input: K = 90Output
11 min read
Article Tags :
Practice Tags :