Next Larger element in n-ary tree

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.

// 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)

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


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

    int x = 5;

    cout << "Next larger element of " << x << " is ";
    cout << nextLargerElement(root, x)->key << endl;

    return 0;


Next larger element of 5 is 6

This article is contributed by Chhavi. If you like GeeksforGeeks and would like to contribute, you can also write an article using or mail your article to 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.

GATE CS Corner    Company Wise Coding Practice

Please write to us at to report any issue with the above content.

Recommended Posts:

0 Average Difficulty : 0/5.0
No votes yet.

Writing code in comment? Please use, generate link and share the link here.