Number of nodes greater than a given value in n-ary tree - GeeksforGeeks

04 Aug, 2021
Given a n-ary tree and a number x, find and return the number of nodes which are greater than x. 
Example: 
In the given tree, x = 7
Number of nodes greater than x are 4.
Approach : The idea is maintain a count variable initialize to 0. Traverse the tree and compare root data with x. If root data is greater than x, increment the count variable and recursively call for all its children. 
Below is the implementation of idea. 
C++
Java
Python3
C#
// C++ program to find number of nodes// greater than x#include <bits/stdc++.h>using namespace std; // Structure of a node of 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;} // Function to find number of nodes// greater than xint nodesGreaterThanX(Node* root, int x){    if (root == NULL)        return 0;     int count = 0;     // if current root is greater    // than x increment count    if (root->key > x)        count++;     // Number of children of root    int numChildren = root->child.size();     // recursively calling for every child    for (int i = 0; i < numChildren; i++) {        Node* child = root->child[i];        count += nodesGreaterThanX(child, x);    }     // return the count    return count;} // 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 << "Number of nodes greater than "        << x << " are ";    cout << nodesGreaterThanX(root, x)        << endl;     return 0;}
// Java program to find number of nodes// greater than ximport java.util.*; // Class representing a Node of an N-ary treeclass Node{         int key;    ArrayList<Node> child;     // Constructor to create a Node    Node(int val)    {        key = val;        child = new ArrayList<>();    }} class GFG{ // Recursive function to find number// of nodes greater than xpublic static int nodesGreaterThanX(Node root, int x){    if (root == null)        return 0;     int count = 0;     // If current root is greater    // than x increment count    if (root.key > x)        count++;     // Recursively calling for every    // child of current root    for(Node child : root.child)    {        count += nodesGreaterThanX(child, x);    }     // Return the count    return count;} // Driver codepublic static void main(String[] args){         /* Let us create below tree            5        / | \        1 2 3        / / \ \    15 4 5 6    */         Node root = new Node(5);         root.child.add(new Node(1));    root.child.add(new Node(2));    root.child.add(new Node(3));         root.child.get(0).child.add(new Node(15));    root.child.get(1).child.add(new Node(4));    root.child.get(1).child.add(new Node(5));    root.child.get(2).child.add(new Node(6));     int x = 5;     System.out.print("Number of nodes greater than " +                    x + " are ");    System.out.println(nodesGreaterThanX(root, x));}} // This code is contributed by jrishabh99
# Python3 program to find number of nodes# greater than x # Structure of a node of n-ary treeclass Node:    def __init__(self, data):        self.key = data        self.child = [] # Function to find number of nodes# greater than xdef nodesGreaterThanX(root: Node, x: int) -> int:    if root is None:        return 0     count = 0     # if current root is greater    # than x increment count    if root.key > x:        count += 1     # Number of children of root    numChildren = len(root.child)     # recursively calling for every child    for i in range(numChildren):        child = root.child[i]        count += nodesGreaterThanX(child, x)     # return the count    return count # Driver Codeif __name__ == "__main__":     ans = 0    k = 25     # Let us create below tree    # 5    #         / | \    # 1 2 3    #     / / \ \    # 15 4 5 6     root = Node(5)    (root.child).append(Node(1))    (root.child).append(Node(2))    (root.child).append(Node(3))    (root.child[0].child).append(Node(15))    (root.child[1].child).append(Node(4))    (root.child[1].child).append(Node(5))    (root.child[2].child).append(Node(6))     x = 5     print("Number of nodes greater than % d are % d" %        (x, nodesGreaterThanX(root, x))) # This code is contributed by# sanjeev2552
// C# program to find number of nodes// greater than xusing System;using System.Collections.Generic;  // Class representing a Node of an N-ary treepublic class Node{    public int key;    public List<Node> child;         // Constructor to create a Node    public Node(int val)    {        key = val;        child = new List<Node>();    }} class GFG{ // Recursive function to find number// of nodes greater than xpublic static int nodesGreaterThanX(Node root, int x){    if (root == null)        return 0;     int count = 0;     // If current root is greater    // than x increment count    if (root.key > x)        count++;     // Recursively calling for every    // child of current root    foreach(Node child in root.child)    {        count += nodesGreaterThanX(child, x);    }     // Return the count    return count;} // Driver codepublic static void Main(String[] args){         /* Let us create below tree          5        / | \       1  2  3      /  / \  \    15  4   5  6    */    Node root = new Node(5);         root.child.Add(new Node(1));    root.child.Add(new Node(2));    root.child.Add(new Node(3));         root.child[0].child.Add(new Node(15));    root.child[1].child.Add(new Node(4));    root.child[1].child.Add(new Node(5));    root.child[2].child.Add(new Node(6));     int x = 5;     Console.Write("Number of nodes greater than " +                  x + " are ");    Console.WriteLine(nodesGreaterThanX(root, x));}} // This code is contributed by Amit Katiyar
Output: 
Number of nodes greater than 5 are 2
YouTubeGeeksforGeeks500K subscribersNumber of nodes greater than a given value 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 / 6:07•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=OpYZ8fbF61g" 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. 
sanjeev2552
jrishabh99
amit143katiyar
AshokJaiswal
anikaseth98
arorakashish0911
n-ary-tree
Tree
Tree
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Inorder Tree Traversal without Recursion
Binary Tree | Set 3 (Types of Binary Tree)
Binary Tree | Set 2 (Properties)
A program to check if a binary tree is BST or not
Decision Tree
Inorder Tree Traversal without recursion and without stack!
Construct Tree from given Inorder and Preorder traversals
Complexity of different operations in Binary tree, Binary Search Tree and AVL tree
Introduction to Tree Data Structure
Lowest Common Ancestor in a Binary Tree | Set 1