Minimum distance between two given nodes in an N-ary tree Last Updated : 16 Sep, 2021 Comments Improve Suggest changes Like Article Like Report Given 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, B = 7Output: 2 Approach: This problem can be solved by using concept of LCA(Lowest Common Ancestor). Minimum distance between two given nodes A and B can be found out by using formula -mindistance(A, B) = dist (LCA, A) + dist (LCA, B)Follow the steps below to solve the problem: Find path from root node to the nodes A and B, respectively and simultaneously store the two paths in two arrays.Now iterate until values of both the arrays are same and value just before mismatch is the LCA node value.The value just before mismatch is the LCA node value.Find distance from the LCA node to node A and B, which can be found with the given steps:In first array, iterate from LCA node value and increase count until value of node A is found, which is dist (LCA, A).In the second array, iterate from LCA node value and increase count until value of node B is found, which is dist (LCA, B)Return the sum of those distances i.e dist (LCA, A) + dist (LCA, B). C++ // C++ program for the above approach #include <bits/stdc++.h> using namespace std; // Structure of Node struct Node { int val; vector<Node*> child; }; // Utility function to create a // new tree node Node* newNode(int key) { Node* temp = new Node; temp->val = key; return temp; } bool flag; // Function to get the path // from root to a node void findPath(Node* root, int key, vector<int>& arr) { if (!root) return; arr.push_back(root->val); // if key is found set flag and return if (root->val == key) { flag = 1; return; } // recur for all children for (int i = 0; i < root->child.size(); i++) { findPath(root->child[i], key, arr); // if key is found dont need to pop values if (flag == 1) return; } arr.pop_back(); return; } void findMinDist(Node* root, int A, int B) { if (root == NULL) return; int val = root->val; // vector to store both paths vector<int> arr1, arr2; // set flag as false; flag = false; // find path from root to node a findPath(root, A, arr1); // set flag again as false; flag = false; // find path from root to node b findPath(root, B, arr2); // to store index of LCA node int j; // if unequal values are found // return previous value for (int i = 1; i < min(arr1.size(), arr2.size()); i++) { if (arr1[i] != arr2[i]) { val = arr1[i - 1]; j = i - 1; break; } } int d1 = 0, d2 = 0; // iterate for finding distance // between LCA(a, b) and a for (int i = j; i < arr1.size(); i++) if (arr1[i] == A) break; else d1 += 1; // iterate for finding distance // between LCA(a, b) and b for (int i = j; i < arr2.size(); i++) if (arr2[i] == B) break; else d2 += 1; // get distance val = d1 + d2; cout << val << '\n'; } // Driver Code int main() { Node* root = newNode(1); (root->child).push_back(newNode(2)); (root->child).push_back(newNode(3)); (root->child[0]->child).push_back(newNode(4)); (root->child[0]->child).push_back(newNode(5)); (root->child[1]->child).push_back(newNode(6)); (root->child[1])->child.push_back(newNode(7)); (root->child[1]->child).push_back(newNode(8)); int A = 4, B = 3; // get min distance findMinDist(root, A, B); return 0; } Java // Java program for the above approach import java.util.*; public class Main { // Structure of Node static class Node { public int val; public Node left, right; public Vector<Node> child; public Node(int key) { val = key; left = right = null; child = new Vector<Node>(); } } // Utility function to create a // new tree node static Node newNode(int key) { Node temp = new Node(key); return temp; } static int flag; // Function to get the path // from root to a node static void findPath(Node root, int key, Vector<Integer> arr) { if (root==null) return; arr.add(root.val); // if key is found set flag and return if (root.val == key) { flag = 1; return; } // recur for all children for (int i = 0; i < root.child.size(); i++) { findPath(root.child.get(i), key, arr); // if key is found dont need to pop values if (flag == 1) return; } arr.remove(arr.size()-1); return; } static void findMinDist(Node root, int A, int B) { if (root == null) return; int val = root.val; // vector to store both paths Vector<Integer> arr1 = new Vector<Integer>(); Vector<Integer> arr2 = new Vector<Integer>(); // set flag as false; flag = 0; // find path from root to node a findPath(root, A, arr1); // set flag again as false; flag = 0; // find path from root to node b findPath(root, B, arr2); // to store index of LCA node int j=0; // if unequal values are found // return previous value for (int i = 1; i < Math.min(arr1.size(), arr2.size()); i++) { if (arr1.get(i) != arr2.get(i)) { val = arr1.get(i - 1); j = i - 1; break; } } int d1 = 0, d2 = 0; // iterate for finding distance // between LCA(a, b) and a for (int i = j; i < arr1.size(); i++) if (arr1.get(i) == A) break; else d1 += 1; // iterate for finding distance // between LCA(a, b) and b for (int i = j; i < arr2.size(); i++) if (arr2.get(i) == B) break; else d2 += 1; // get distance val = d1 + d2; System.out.println(val); } public static void main(String[] args) { Node root = newNode(1); (root.child).add(newNode(2)); (root.child).add(newNode(3)); (root.child.get(0).child).add(newNode(4)); (root.child.get(0).child).add(newNode(5)); (root.child.get(1).child).add(newNode(6)); (root.child.get(1)).child.add(newNode(7)); (root.child.get(1).child).add(newNode(8)); int A = 4, B = 3; // get min distance findMinDist(root, A, B); } } // This code is contributed by mukesh07. Python3 # Python3 program for the above approach # Structure of Node class Node: def __init__(self, key): self.val = key self.left = None self.right = None self.child = [] # Utility function to create a # new tree node def newNode(key): temp = Node(key) return temp flag = 0 # Function to get the path # from root to a node def findPath(root, key, arr): global flag if (root==None): return arr.append(root.val) # if key is found set flag and return if (root.val == key): flag = 1 return # recur for all children for i in range(len(root.child)): findPath(root.child[i], key, arr) # if key is found dont need to pop values if (flag == 1): return arr.pop() return def findMinDist(root, A, B): global flag if (root == None): return val = root.val # vector to store both paths arr1 = [] arr2 = [] # set flag as false; flag = 0 # find path from root to node a findPath(root, A, arr1) # set flag again as false; flag = 0 # find path from root to node b findPath(root, B, arr2) # to store index of LCA node j=0 # if unequal values are found # return previous value for i in range(min(len(arr1), len(arr2))): if (arr1[i] != arr2[i]): val = arr1[i - 1] j = i - 1 break d1, d2 = 0, 0 # iterate for finding distance # between LCA(a, b) and a for i in range(j, len(arr1)): if (arr1[i] == A): break else: d1 += 1 # iterate for finding distance # between LCA(a, b) and b for i in range(j, len(arr2)): if (arr2[i] == B): break else: d2 += 1 # get distance val = d1 + d2 print(val) root = newNode(1) (root.child).append(newNode(2)) (root.child).append(newNode(3)) (root.child[0].child).append(newNode(4)) (root.child[0].child).append(newNode(5)) (root.child[1].child).append(newNode(6)) (root.child[1]).child.append(newNode(7)) (root.child[1].child).append(newNode(8)) A, B = 4, 3 # get min distance findMinDist(root, A, B) # This code is contributed by rameshtravel07. C# // C# program for the above approach using System; using System.Collections.Generic; // Structure of Node class GFG{ public class Node { public int val; public Node left=null, right=null; public List<Node> child = new List<Node>(); } // Utility function to create a // new tree node static Node newNode(int key) { Node temp = new Node(); temp.val = key; return temp; } static int flag; // Function to get the path // from root to a node static void findPath(Node root, int key, List<int> arr) { if (root==null) return; arr.Add(root.val); // if key is found set flag and return if (root.val == key) { flag = 1; return; } // recur for all children for (int i = 0; i < root.child.Count; i++) { findPath(root.child[i], key, arr); // if key is found dont need to pop values if (flag == 1) return; } arr.RemoveAt(arr.Count-1); return; } static void findMinDist(Node root, int A, int B) { if (root == null) return; int val = root.val; // vector to store both paths List<int> arr1 = new List<int>(); List<int> arr2 = new List<int>(); // set flag as false; flag = 0; // find path from root to node a findPath(root, A, arr1); // set flag again as false; flag = 0; // find path from root to node b findPath(root, B, arr2); // to store index of LCA node int j=0; // if unequal values are found // return previous value for (int i = 1; i < Math.Min(arr1.Count, arr2.Count); i++) { if (arr1[i] != arr2[i]) { val = arr1[i - 1]; j = i - 1; break; } } int d1 = 0, d2 = 0; // iterate for finding distance // between LCA(a, b) and a for (int i = j; i < arr1.Count; i++) if (arr1[i] == A) break; else d1 += 1; // iterate for finding distance // between LCA(a, b) and b for (int i = j; i < arr2.Count; i++) if (arr2[i] == B) break; else d2 += 1; // get distance val = d1 + d2; Console.WriteLine(val); } // Driver Code public static void Main() { Node root = newNode(1); (root.child).Add(newNode(2)); (root.child).Add(newNode(3)); (root.child[0].child).Add(newNode(4)); (root.child[0].child).Add(newNode(5)); (root.child[1].child).Add(newNode(6)); (root.child[1]).child.Add(newNode(7)); (root.child[1].child).Add(newNode(8)); int A = 4, B = 3; // get min distance findMinDist(root, A, B); } } // This code is contributed by SURENDRA_GANGWAR. JavaScript <script> // Javascript program for the above approach // Structure of Node class Node { constructor(key) { this.left = null; this.right = null; this.val = key; this.child = []; } } // Utility function to create a // new tree node function newNode(key) { let temp = new Node(key); return temp; } let flag; // Function to get the path // from root to a node function findPath(root, key, arr) { if (root==null) return; arr.push(root.val); // if key is found set flag and return if (root.val == key) { flag = 1; return; } // recur for all children for (let i = 0; i < root.child.length; i++) { findPath(root.child[i], key, arr); // if key is found dont need to pop values if (flag == 1) return; } arr.pop(); return; } function findMinDist(root, A, B) { if (root == null) return; let val = root.val; // vector to store both paths let arr1 = []; let arr2 = []; // set flag as false; flag = 0; // find path from root to node a findPath(root, A, arr1); // set flag again as false; flag = 0; // find path from root to node b findPath(root, B, arr2); // to store index of LCA node let j=0; // if unequal values are found // return previous value for (let i = 1; i < Math.min(arr1.length, arr2.length); i++) { if (arr1[i] != arr2[i]) { val = arr1[i - 1]; j = i - 1; break; } } let d1 = 0, d2 = 0; // iterate for finding distance // between LCA(a, b) and a for (let i = j; i < arr1.length; i++) if (arr1[i] == A) break; else d1 += 1; // iterate for finding distance // between LCA(a, b) and b for (let i = j; i < arr2.length; i++) if (arr2[i] == B) break; else d2 += 1; // get distance val = d1 + d2; document.write(val); } let root = newNode(1); (root.child).push(newNode(2)); (root.child).push(newNode(3)); (root.child[0].child).push(newNode(4)); (root.child[0].child).push(newNode(5)); (root.child[1].child).push(newNode(6)); (root.child[1]).child.push(newNode(7)); (root.child[1].child).push(newNode(8)); let A = 4, B = 3; // get min distance findMinDist(root, A, B); // This code is contributed by decode2207. </script> Output3 Time complexity: O(N).Auxiliary Space: O(N). Comment More infoAdvertise with us Next Article Average width in a N-ary tree S sohailahmed46khan786 Follow Improve Article Tags : Misc Tree DSA Tree Traversals 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