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.

Algorithm

  • 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.

Implementation

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) {
      return;
   }
   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);
   }
   return;
}
int main() {
   Node* root = newNode(10);
   root->child.push_back(newNode(12));
   root->child.push_back(newNode(23));
   root->child.push_back(newNode(45));
   root->child[0]->child.push_back(newNode(40));
   root->child[1]->child.push_back(newNode(33));
   root->child[2]->child.push_back(newNode(12));
   Node* result = NULL;
   findNextGreaterElement(root, 20, &result);
   cout << result->data << endl;
   return 0;
}

Output

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

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

Advertisements