Next Larger element in n-ary tree in C++

C++Server Side ProgrammingProgramming

The n-ary tree is the tree with n children for each node. We are given a number n and we have to find the next larger element from the n-ary tree.

We can find the solution by traversing through the n-ary tree and maintaining the result.


  • Create n-ary tree.
  • Initialise a result.
  • Write a function to get next larger element.
    • Return if the current node is null.
    • Check the current node data is greater than the expected element or not.
    • If yes, then check whether the result is empty or the result is greater than the current node data.
    • If the above condition satisfies, then update the result.
    • Get the current node children.
    • Iterate over the children.
      • Call the recursive function.

We are updating the result every time we find an element that is greater than the given number and less than the result. It ensures that we get the next larger element in the end.


Following is the implementation of the above algorithm in C++

#include <bits/stdc++.h>
using namespace std;
struct Node {
   int data;
   vector<Node*> child;
Node* newNode(int data) {
   Node* newNode = new Node;
   newNode->data = data;
   return newNode;
void findNextGreaterElement(Node* root, int x, Node** result) {
   if (root == NULL) {
   if (root->data > x) {
      if (!(*result) || (*result)->data > root->data) {
         *result = root;
   int childCount = root->child.size();
   for (int i = 0; i < childCount; i++) {
      findNextGreaterElement(root->child[i], x, result);
int main() {
   Node* root = newNode(10);
   Node* result = NULL;
   findNextGreaterElement(root, 20, &result);
   cout << result->data << endl;
   return 0;


If you run the above code, then you will get the following result.

Updated on 25-Oct-2021 04:01:50