Count of nodes in a given N-ary tree having distance to all leaf nodes equal in their subtree Last Updated : 11 Jan, 2022 Summarize Comments Improve Suggest changes Share Like Article Like Report Given an N-ary tree root, the task is to find the number of non-leaf nodes in the tree such that all the leaf nodes in the subtree of the current node are at an equal distance from the current node. Example: Input: Tree in the below imageOutput: 4Explanation: The nodes {10, 3, 2, 4} have the distance between them and all the leaf nodes in their subtree respectively as equal. Input: Tree in the image belowOutput: 3 Approach: The given problem can be solved by using the post-order traversal. The idea is to check if the number of nodes from the current node to all its leaf nodes is the same. Below steps can be followed to solve the problem: Apply post-order traversal on the N-ary tree:If the root has no children then return 1 to the parentIf every branch has equal height then increment the count by 1 and return height + 1 to the parentOr else return -1 to the parent indicating that the branches have unequal heightReturn the count as the answer C++ // C++ code for the above approach #include <bits/stdc++.h> using namespace std; class Node { public: vector<Node*> children; int val; // constructor Node(int v) { val = v; children = {}; } }; // Post-order traversal to find // depth of all branches of every // node of the tree int postOrder(Node* root, int count[]) { // If root is a leaf node // then return 1 if (root->children.size() == 0) return 1; // Initialize a variable height // calculate longest increasing path int height = 0; // Use recursion on all child nodes for (Node* child : root->children) { // Get the height of the branch int h = postOrder(child, count); // Initialize height of first // explored branch if (height == 0) height = h; // If branches are unbalanced // then store -1 in height else if (h == -1 || height != h) height = -1; } // Increment the value of count // If height is not -1 if (height != -1) count[0]++; // Return the height of branches // including the root if height is // not -1 or else return -1 return height != -1 ? height + 1 : -1; } // Function to find the number of nodes // in the N-ary tree with their branches // having equal height int equalHeightBranches(Node* root) { // Base case if (root == NULL) return 0; // Initialize a variable count // to store the answer int count[1] = { 0 }; // Apply post order traversal // on the tree postOrder(root, count); // Return the answer return count[0]; } // Driver code int main() { // Initialize the tree Node* seven = new Node(7); Node* seven2 = new Node(7); Node* five = new Node(5); Node* four = new Node(4); Node* nine = new Node(9); Node* one = new Node(1); Node* two = new Node(2); Node* six = new Node(6); Node* eight = new Node(8); Node* ten = new Node(10); Node* three = new Node(3); Node* mfour = new Node(-4); Node* mtwo = new Node(-2); Node* zero = new Node(0); three->children.push_back(mfour); three->children.push_back(mtwo); three->children.push_back(zero); ten->children.push_back(three); two->children.push_back(six); two->children.push_back(seven2); four->children.push_back(nine); four->children.push_back(one); four->children.push_back(five); seven->children.push_back(ten); seven->children.push_back(two); seven->children.push_back(eight); seven->children.push_back(four); // Call the function // and print the result cout << (equalHeightBranches(seven)); } // This code is contributed by Potta Lokesh Java // Java implementation for the above approach import java.io.*; import java.util.*; class GFG { // Function to find the number of nodes // in the N-ary tree with their branches // having equal height public static int equalHeightBranches(Node root) { // Base case if (root == null) return 0; // Initialize a variable count // to store the answer int[] count = new int[1]; // Apply post order traversal // on the tree postOrder(root, count); // Return the answer return count[0]; } // Post-order traversal to find // depth of all branches of every // node of the tree public static int postOrder( Node root, int[] count) { // If root is a leaf node // then return 1 if (root.children.size() == 0) return 1; // Initialize a variable height // calculate longest increasing path int height = 0; // Use recursion on all child nodes for (Node child : root.children) { // Get the height of the branch int h = postOrder(child, count); // Initialize height of first // explored branch if (height == 0) height = h; // If branches are unbalanced // then store -1 in height else if (h == -1 || height != h) height = -1; } // Increment the value of count // If height is not -1 if (height != -1) count[0]++; // Return the height of branches // including the root if height is // not -1 or else return -1 return height != -1 ? height + 1 : -1; } // Driver code public static void main(String[] args) { // Initialize the tree Node seven = new Node(7); Node seven2 = new Node(7); Node five = new Node(5); Node four = new Node(4); Node nine = new Node(9); Node one = new Node(1); Node two = new Node(2); Node six = new Node(6); Node eight = new Node(8); Node ten = new Node(10); Node three = new Node(3); Node mfour = new Node(-4); Node mtwo = new Node(-2); Node zero = new Node(0); three.children.add(mfour); three.children.add(mtwo); three.children.add(zero); ten.children.add(three); two.children.add(six); two.children.add(seven2); four.children.add(nine); four.children.add(one); four.children.add(five); seven.children.add(ten); seven.children.add(two); seven.children.add(eight); seven.children.add(four); // Call the function // and print the result System.out.println( equalHeightBranches(seven)); } static class Node { List<Node> children; int val; // constructor public Node(int val) { this.val = val; children = new ArrayList<>(); } } } Python3 # Python code for the above approach class Node: def __init__(self, val): self.val = val self.children = [] # Post-order traversal to find # depth of all branches of every # node of the tree def postOrder(root, count): # If root is a leaf node # then return 1 if (len(root.children) == 0): return 1 # Initialize a variable height # calculate longest increasing path height = 0 # Use recursion on all child nodes for child in root.children: # Get the height of the branch h = postOrder(child, count) # Initialize height of first # explored branch if (height == 0): height = h # If branches are unbalanced # then store -1 in height elif (h == -1 or height != h): height = -1 # Increment the value of count # If height is not -1 if (height != -1): count[0] += 1 # Return the height of branches # including the root if height is # not -1 or else return -1 if(height != -1): return height + 1 else: return -1 # Function to find the number of nodes # in the N-ary tree with their branches # having equal height def equalHeightBranches(root): # Base case if (root == None): return 0 # Initialize a variable count # to store the answer count = [0] # Apply post order traversal # on the tree postOrder(root, count) # Return the answer return count[0] # Driver code # Initialize the tree seven = Node(7) seven2 = Node(7) five = Node(5) four = Node(4) nine = Node(9) one = Node(1) two = Node(2) six = Node(6) eight = Node(8) ten = Node(10) three = Node(3) mfour = Node(-4) mtwo = Node(-2) zero = Node(0) three.children.append(mfour) three.children.append(mtwo) three.children.append(zero) ten.children.append(three) two.children.append(six) two.children.append(seven2) four.children.append(nine) four.children.append(one) four.children.append(five) seven.children.append(ten) seven.children.append(two) seven.children.append(eight) seven.children.append(four) # Call the function # and print the result print(equalHeightBranches(seven)) # This code is contributed by rj13to. C# // C# implementation for the above approach using System; using System.Collections.Generic; public class Node { public int val; public List<Node> children; // Constructor to create a Node public Node(int vall) { val = vall; children = new List<Node>(); } } class GFG { // Function to find the number of nodes // in the N-ary tree with their branches // having equal height public static int equalHeightBranches(Node root) { // Base case if (root == null) return 0; // Initialize a variable count // to store the answer int[] count = new int[1]; // Apply post order traversal // on the tree postOrder(root, count); // Return the answer return count[0]; } // Post-order traversal to find // depth of all branches of every // node of the tree public static int postOrder( Node root, int[] count) { // If root is a leaf node // then return 1 if (root.children.Count == 0) return 1; // Initialize a variable height // calculate longest increasing path int height = 0; // Use recursion on all child nodes foreach (Node child in root.children) { // Get the height of the branch int h = postOrder(child, count); // Initialize height of first // explored branch if (height == 0) height = h; // If branches are unbalanced // then store -1 in height else if (h == -1 || height != h) height = -1; } // Increment the value of count // If height is not -1 if (height != -1) count[0]++; // Return the height of branches // including the root if height is // not -1 or else return -1 return height != -1 ? height + 1 : -1; } // Driver code public static void Main() { // Initialize the tree Node seven = new Node(7); Node seven2 = new Node(7); Node five = new Node(5); Node four = new Node(4); Node nine = new Node(9); Node one = new Node(1); Node two = new Node(2); Node six = new Node(6); Node eight = new Node(8); Node ten = new Node(10); Node three = new Node(3); Node mfour = new Node(-4); Node mtwo = new Node(-2); Node zero = new Node(0); three.children.Add(mfour); three.children.Add(mtwo); three.children.Add(zero); ten.children.Add(three); two.children.Add(six); two.children.Add(seven2); four.children.Add(nine); four.children.Add(one); four.children.Add(five); seven.children.Add(ten); seven.children.Add(two); seven.children.Add(eight); seven.children.Add(four); // Call the function // and print the result Console.WriteLine( equalHeightBranches(seven)); } } // This code is contributed // by Shubham Singh JavaScript <script> // Javascript implementation for the above approach class Node { // constructor constructor(val) { this.val = val; this.children = []; } } // Function to find the number of nodes // in the N-ary tree with their branches // having equal height function equalHeightBranches(root) { // Base case if (root == null) return 0; // Initialize a variable count // to store the answer let count = [0]; // Apply post order traversal // on the tree postOrder(root, count); // Return the answer return count[0]; } // Post-order traversal to find // depth of all branches of every // let of the tree function postOrder(root, count) { // If root is a leaf node // then return 1 if (root.children.length == 0) return 1; // Initialize a variable height // calculate longest increasing path let height = 0; // Use recursion on all child nodes for (child of root.children) { // Get the height of the branch let h = postOrder(child, count); // Initialize height of first // explored branch if (height == 0) height = h; // If branches are unbalanced // then store -1 in height else if (h == -1 || height != h) height = -1; } // Increment the value of count // If height is not -1 if (height != -1) count[0]++; // Return the height of branches // including the root if height is // not -1 or else return -1 return height != -1 ? height + 1 : -1; } // Driver code // Initialize the tree let seven = new Node(7); let seven2 = new Node(7); let five = new Node(5); let four = new Node(4); let nine = new Node(9); let one = new Node(1); let two = new Node(2); let six = new Node(6); let eight = new Node(8); let ten = new Node(10); let three = new Node(3); let mfour = new Node(-4); let mtwo = new Node(-2); let zero = new Node(0); three.children.push(mfour); three.children.push(mtwo); three.children.push(zero); ten.children.push(three); two.children.push(six); two.children.push(seven2); four.children.push(nine); four.children.push(one); four.children.push(five); seven.children.push(ten); seven.children.push(two); seven.children.push(eight); seven.children.push(four); // Call the function // and print the result console.log(equalHeightBranches(seven)); // This code is contributed by gfgking. </script> Output4 Time Complexity: O(N)Auxiliary Space: O(H), where H is the height of the tree Comment More infoAdvertise with us Next Article Count of nodes in a given N-ary tree having distance to all leaf nodes equal in their subtree A athakur42u Follow Improve Article Tags : Misc Tree DSA tree-traversal n-ary-tree +1 More Practice Tags : MiscTree Similar Reads Introduction to Generic Trees (N-ary Trees) Generic trees are a collection of nodes where each node is a data structure that consists of records and a list of references to its children(duplicate references are not allowed). Unlike the linked list, each node stores the address of multiple nodes. Every node stores address of its children and t 5 min read What is Generic Tree or N-ary Tree? Generic tree or an N-ary tree is a versatile data structure used to organize data hierarchically. Unlike binary trees that have at most two children per node, generic trees can have any number of child nodes. This flexibility makes them suitable for representing hierarchical data where each node can 4 min read N-ary Tree TraversalsInorder traversal of an N-ary TreeGiven an N-ary tree containing, the task is to print the inorder traversal of the tree. Examples: Input: N = 3  Output: 5 6 2 7 3 1 4Input: N = 3  Output: 2 3 5 1 4 6 Approach: The inorder traversal of an N-ary tree is defined as visiting all the children except the last then the root and finall 6 min read Preorder Traversal of an N-ary TreeGiven an N-ary Tree. The task is to write a program to perform the preorder traversal of the given n-ary tree. Examples: Input: 3-Array Tree 1 / | \ / | \ 2 3 4 / \ / | \ 5 6 7 8 9 / / | \ 10 11 12 13 Output: 1 2 5 10 6 11 12 13 3 4 7 8 9 Input: 3-Array Tree 1 / | \ / | \ 2 3 4 / \ / | \ 5 6 7 8 9 O 14 min read Iterative Postorder Traversal of N-ary TreeGiven an N-ary tree, the task is to find the post-order traversal of the given tree iteratively.Examples: Input: 1 / | \ 3 2 4 / \ 5 6 Output: [5, 6, 3, 2, 4, 1] Input: 1 / \ 2 3 Output: [2, 3, 1] Approach:We have already discussed iterative post-order traversal of binary tree using one stack. We wi 10 min read Level Order Traversal of N-ary TreeGiven an N-ary Tree. The task is to print the level order traversal of the tree where each level will be in a new line. Examples: Input: Image Output: 13 2 45 6Explanation: At level 1: only 1 is present.At level 2: 3, 2, 4 is presentAt level 3: 5, 6 is present Input: Image Output: 12 3 4 56 7 8 9 10 11 min read ZigZag Level Order Traversal of an N-ary TreeGiven a Generic Tree consisting of n nodes, the task is to find the ZigZag Level Order Traversal of the given tree.Note: A generic tree is a tree where each node can have zero or more children nodes. Unlike a binary tree, which has at most two children per node (left and right), a generic tree allow 8 min read Depth of an N-Ary tree Given an n-ary tree containing positive node values, the task is to find the depth of the tree.Note: An n-ary tree is a tree where each node can have zero or more children nodes. Unlike a binary tree, which has at most two children per node (left and right), the n-ary tree allows for multiple branch 5 min read Mirror of n-ary Tree Given a Tree where every node contains variable number of children, convert the tree to its mirror. Below diagram shows an example. We strongly recommend you to minimize your browser and try this yourself first. Node of tree is represented as a key and a variable sized array of children pointers. Th 9 min read Insertion in n-ary tree in given order and Level order traversal Given a set of parent nodes where the index of the array is the child of each Node value, the task is to insert the nodes as a forest(multiple trees combined together) where each parent could have more than two children. After inserting the nodes, print each level in a sorted format. Example: Input: 10 min read Diameter of an N-ary tree The diameter of an N-ary tree is the longest path present between any two nodes of the tree. These two nodes must be two leaf nodes. The following examples have the longest path[diameter] shaded. Example 1: Example 2: Prerequisite: Diameter of a binary tree. The path can either start from one of th 15+ min read Sum of all elements of N-ary Tree Given an n-ary tree consisting of n nodes, the task is to find the sum of all the elements in the given n-ary tree.Example:Input:Output: 268Explanation: The sum of all the nodes is 11 + 21 + 29 + 90 + 18 + 10 + 12 + 77 = 268Input:Output: 360Explanation: The sum of all the nodes is 81 + 26 + 23 + 49 5 min read Serialize and Deserialize an N-ary Tree Given an N-ary tree where every node has the most N children. How to serialize and deserialize it? Serialization is to store a tree in a file so that it can be later restored. The structure of the tree must be maintained. Deserialization is reading the tree back from the file. This post is mainly an 11 min read Easy problems on n-ary TreeCheck if the given n-ary tree is a binary treeGiven an n-ary tree consisting of n nodes, the task is to check whether the given tree is binary or not.Note: An n-ary tree is a tree where each node can have zero or more children nodes. Unlike a binary tree, which has at most two children per node (left and right), the n-ary tree allows for multip 6 min read Largest element in an N-ary TreeGiven an n-ary tree containing positive node values, the task is to find the node with the largest value in the given n-ary tree.Note: An n-ary tree is a tree where each node can have zero or more children nodes. Unlike a binary tree, which has at most two children per node (left and right), the n-a 5 min read Second Largest element in n-ary treeGiven an n-ary tree containing positive node values, the task is to find the node with the second largest value in the given n-ary tree. If there is no second largest node return -1.Note: An n-ary tree is a tree where each node can have zero or more children nodes. Unlike a binary tree, which has at 7 min read Number of children of given node in n-ary TreeGiven a node x, find the number of children of x(if it exists) in the given n-ary tree. Example : Input : x = 50 Output : 3 Explanation : 50 has 3 children having values 40, 100 and 20. Approach : Initialize the number of children as 0.For every node in the n-ary tree, check if its value is equal to 7 min read Number of nodes greater than a given value in n-ary treeGiven 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 gr 6 min read Check mirror in n-ary treeGiven two n-ary trees, determine whether they are mirror images of each other. Each tree is described by e edges, where e denotes the number of edges in both trees. Two arrays A[]and B[] are provided, where each array contains 2*e space-separated values representing the edges of both trees. Each edg 11 min read Replace every node with depth in N-ary Generic TreeGiven an array arr[] representing a Generic(N-ary) tree. The task is to replace the node data with the depth(level) of the node. Assume level of root to be 0. Array Representation: The N-ary tree is serialized in the array arr[] using level order traversal as described below:  The input is given as 15+ min read Preorder Traversal of N-ary Tree Without RecursionGiven an n-ary tree containing positive node values. The task is to print the preorder traversal without using recursion.Note: An n-ary tree is a tree where each node can have zero or more children. Unlike a binary tree, which has at most two children per node (left and right), the n-ary tree allows 6 min read Maximum value at each level in an N-ary TreeGiven a N-ary Tree consisting of nodes valued in the range [0, N - 1] and an array arr[] where each node i is associated to value arr[i], the task is to print the maximum value associated with any node at each level of the given N-ary Tree. Examples: Input: N = 8, Edges[][] = {{0, 1}, {0, 2}, {0, 3} 9 min read Replace each node in given N-ary Tree with sum of all its subtreesGiven an N-ary tree. The task is to replace the values of each node with the sum of all its subtrees and the node itself. Examples Input: 1 / | \ 2 3 4 / \ \ 5 6 7Output: Initial Pre-order Traversal: 1 2 5 6 7 3 4 Final Pre-order Traversal: 28 20 5 6 7 3 4 Explanation: Value of each node is replaced 8 min read Path from the root node to a given node in an N-ary TreeGiven an integer N and an N-ary Tree of the following form: Every node is numbered sequentially, starting from 1, till the last level, which contains the node N.The nodes at every odd level contains 2 children and nodes at every even level contains 4 children. The task is to print the path from the 10 min read Determine the count of Leaf nodes in an N-ary treeGiven the value of 'N' and 'I'. Here, I represents the number of internal nodes present in an N-ary tree and every node of the N-ary can either have N childs or zero child. The task is to determine the number of Leaf nodes in n-ary tree. Examples: Input : N = 3, I = 5 Output : Leaf nodes = 11 Input 4 min read Remove all leaf nodes from a Generic Tree or N-ary TreeGiven an n-ary tree containing positive node values, the task is to delete all the leaf nodes from the tree and print preorder traversal of the tree after performing the deletion.Note: An n-ary tree is a tree where each node can have zero or more children nodes. Unlike a binary tree, which has at mo 6 min read Maximum level sum in N-ary TreeGiven an N-ary Tree consisting of nodes valued [1, N] and an array value[], where each node i is associated with value[i], the task is to find the maximum of sum of all node values of all levels of the N-ary Tree. Examples: Input: N = 8, Edges[][2] = {{0, 1}, {0, 2}, {0, 3}, {1, 4}, {1, 5}, {3, 6}, 9 min read Number of leaf nodes in a perfect N-ary tree of height KFind the number of leaf nodes in a perfect N-ary tree of height K. Note: As the answer can be very large, return the answer modulo 109+7. Examples: Input: N = 2, K = 2Output: 4Explanation: A perfect Binary tree of height 2 has 4 leaf nodes. Input: N = 2, K = 1Output: 2Explanation: A perfect Binary t 4 min read Print all root to leaf paths of an N-ary treeGiven an N-Ary tree, the task is to print all root to leaf paths of the given N-ary Tree. Examples: Input: 1 / \ 2 3 / / \ 4 5 6 / \ 7 8 Output:1 2 41 3 51 3 6 71 3 6 8 Input: 1 / | \ 2 5 3 / \ \ 4 5 6Output:1 2 41 2 51 51 3 6 Approach: The idea to solve this problem is to start traversing the N-ary 7 min read Minimum distance between two given nodes in an N-ary treeGiven a N ary Tree consisting of N nodes, the task is to find the minimum distance from node A to node B of the tree. Examples: Input: 1 / \ 2 3 / \ / \ \4 5 6 7 8A = 4, B = 3Output: 3Explanation: The path 4->2->1->3 gives the minimum distance from A to B. Input: 1 / \ 2 3 / \ \ 6 7 8A = 6, 11 min read Average width in a N-ary treeGiven a Generic Tree consisting of N nodes, the task is to find the average width for each node present in the given tree. The average width for each node can be calculated by the ratio of the total number of nodes in that subtree(including the node itself) to the total number of levels under that n 8 min read Maximum width of an N-ary treeGiven an N-ary tree, the task is to find the maximum width of the given tree. The maximum width of a tree is the maximum of width among all levels. Examples: Input: 4 / | \ 2 3 -5 / \ /\ -1 3 -2 6 Output: 4 Explanation: Width of 0th level is 1. Width of 1st level is 3. Width of 2nd level is 4. There 9 min read Like