Next Larger element in n-ary tree

08 Jul, 2021
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
 
Chapters
descriptions off, selected
captions settings, opens captions settings dialog
captions off, selected
English
This is a modal window.
Beginning of dialog window. Escape will cancel and close the window.
End of dialog window.
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. 
C++
Java
Python3
C#
Javascript
// 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 treestruct Node {    int key;    vector<Node*> child;}; // Utility function to create a new tree nodeNode* 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 treeNode* nextLargerElement(Node* root, int x){    // resultant node    Node* res = NULL;     // calling helper function    nextLargerElementUtil(root, x, &res);     return res;} // Driver programint 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 program to find next larger element// in an n-ary tree.import java.util.*; class GFG{ // Structure of a node of an n-ary treestatic class Node{    int key;    Vector<Node> child;};static Node res; // Utility function to create a new tree nodestatic 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 treestatic Node nextLargerElement(Node root, int x){    // resultant node    res = null;     // calling helper function    nextLargerElementUtil(root, x);     return res;} // Driver Codepublic 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 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 nodedef 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 treedef nextLargerElement(root,x):      # resultant node    global res    res=None         # Calling helper function    nextLargerElementUtil(root, x)         return res         # Driver coderoot = 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 = 5print("Next larger element of " , x , " is ",end='')print(nextLargerElement(root, x).key) # This code is contributed by rag2127.
// 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 treeclass Node{    public int key;    public List<Node> child;};static Node res; // Utility function to create a new tree nodestatic 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 treestatic Node nextLargerElement(Node root,                                     int x){    // resultant node    res = null;     // calling helper function    nextLargerElementUtil(root, x);     return res;} // Driver Codepublic 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
<script> // JavaScript program to find next larger element// in an n-ary tree. // Structure of a node of an n-ary treeclass Node{    constructor()    {        this.key = 0;        this.child = [];    }}; var res = null; // Utility function to create a new tree nodefunction 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 treefunction 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;document.write("Next larger element of " +                             x + " is ");document.write(nextLargerElement(root, x).key + "<br>");  </script>
Output:  
Next larger element of 5 is 6
 
Next Larger element in n-ary tree | GeeksforGeeks - YouTubeGeeksforGeeks529K subscribersNext Larger element in n-ary tree | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 4:06•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=MB665oPA7SE" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
This article is contributed by Chhavi. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. 
29AjayKumar
princiraj1992
rrrtnx
rag2127
n-ary-tree
Tree
Tree
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Tree Traversals (Inorder, Preorder and Postorder)
Binary Tree | Set 1 (Introduction)
Level Order Binary Tree Traversal
AVL Tree | Set 1 (Insertion)
Introduction to Data Structures
Introduction to Tree Data Structure
Inorder Tree Traversal without Recursion
What is Data Structure: Types, Classifications and Applications
Write a Program to Find the Maximum Depth or Height of a Tree
Binary Tree | Set 3 (Types of Binary Tree)