Diameter of an N-ary tree
Last Updated :
27 Mar, 2024
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 the nodes and go up to one of the LCAs of these nodes and again come down to the deepest node of some other subtree or can exist as a diameter of one of the child of the current node.
The solution will exist in any one of these:
- Diameter of one of the children of the current node
- Sum of Height of the highest two subtree + 1
Implementation:
C++
// C++ program to find the height of an N-ary
// tree
#include <bits/stdc++.h>
using namespace std;
// Structure of a node of an n-ary tree
struct Node
{
char key;
vector<Node *> child;
};
// Utility function to create a new tree node
Node *newNode(int key)
{
Node *temp = new Node;
temp->key = key;
return temp;
}
// Utility function that will return the depth
// of the tree
int depthOfTree(struct Node *ptr)
{
// Base case
if (!ptr)
return 0;
int maxdepth = 0;
// Check for all children and find
// the maximum depth
for (vector<Node*>::iterator it = ptr->child.begin();
it != ptr->child.end(); it++)
maxdepth = max(maxdepth , depthOfTree(*it));
return maxdepth + 1;
}
// Function to calculate the diameter
// of the tree
int diameter(struct Node *ptr)
{
// Base case
if (!ptr)
return 0;
// Find top two highest children
int max1 = 0, max2 = 0;
for (vector<Node*>::iterator it = ptr->child.begin();
it != ptr->child.end(); it++)
{
int h = depthOfTree(*it);
if (h > max1)
max2 = max1, max1 = h;
else if (h > max2)
max2 = h;
}
// Iterate over each child for diameter
int maxChildDia = 0;
for (vector<Node*>::iterator it = ptr->child.begin();
it != ptr->child.end(); it++)
maxChildDia = max(maxChildDia, diameter(*it));
return max(maxChildDia, max1 + max2 + 1);
}
// Driver program
int main()
{
/* Let us create below tree
* A
* / / \ \
* B F D E
* / \ | /|\
* K J G C H I
* /\ \
* N M L
*/
Node *root = newNode('A');
(root->child).push_back(newNode('B'));
(root->child).push_back(newNode('F'));
(root->child).push_back(newNode('D'));
(root->child).push_back(newNode('E'));
(root->child[0]->child).push_back(newNode('K'));
(root->child[0]->child).push_back(newNode('J'));
(root->child[2]->child).push_back(newNode('G'));
(root->child[3]->child).push_back(newNode('C'));
(root->child[3]->child).push_back(newNode('H'));
(root->child[3]->child).push_back(newNode('I'));
(root->child[0]->child[0]->child).push_back(newNode('N'));
(root->child[0]->child[0]->child).push_back(newNode('M'));
(root->child[3]->child[2]->child).push_back(newNode('L'));
cout << diameter(root) << endl;
return 0;
}
Java
// Java program to find the height of an N-ary
// tree
import java.util.*;
class GFG
{
// Structure of a node of an n-ary tree
static class Node
{
char key;
Vector<Node> child;
};
// Utility function to create a new tree node
static Node newNode(int key)
{
Node temp = new Node();
temp.key = (char) key;
temp.child = new Vector<Node>();
return temp;
}
// Utility function that will return the depth
// of the tree
static int depthOfTree(Node ptr)
{
// Base case
if (ptr == null)
return 0;
int maxdepth = 0;
// Check for all children and find
// the maximum depth
for (Node it : ptr.child)
maxdepth = Math.max(maxdepth,
depthOfTree(it));
return maxdepth + 1;
}
// Function to calculate the diameter
// of the tree
static int diameter(Node ptr)
{
// Base case
if (ptr == null)
return 0;
// Find top two highest children
int max1 = 0, max2 = 0;
for (Node it : ptr.child)
{
int h = depthOfTree(it);
if (h > max1)
{
max2 = max1;
max1 = h;
}
else if (h > max2)
max2 = h;
}
// Iterate over each child for diameter
int maxChildDia = 0;
for (Node it : ptr.child)
maxChildDia = Math.max(maxChildDia,
diameter(it));
return Math.max(maxChildDia, max1 + max2 + 1);
}
// Driver Code
public static void main(String[] args)
{
/* Let us create below tree
* A
* / / \ \
* B F D E
* / \ | /|\
* K J G C H I
* /\ \
* N M L
*/
Node root = newNode('A');
(root.child).add(newNode('B'));
(root.child).add(newNode('F'));
(root.child).add(newNode('D'));
(root.child).add(newNode('E'));
(root.child.get(0).child).add(newNode('K'));
(root.child.get(0).child).add(newNode('J'));
(root.child.get(2).child).add(newNode('G'));
(root.child.get(3).child).add(newNode('C'));
(root.child.get(3).child).add(newNode('H'));
(root.child.get(3).child).add(newNode('I'));
(root.child.get(0).child.get(0).child).add(newNode('N'));
(root.child.get(0).child.get(0).child).add(newNode('M'));
(root.child.get(3).child.get(2).child).add(newNode('L'));
System.out.print(diameter(root) + "\n");
}
}
// This code is contributed by Rajput-Ji
Python3
# Python program to find the height of an N-ary
# tree
# Structure of a node of an n-ary tree
class Node:
def __init__(self, x):
self.key = x
self.child = []
# Utility function that will return the depth
# of the tree
def depthOfTree(ptr):
# Base case
if (not ptr):
return 0
maxdepth = 0
# Check for all children and find
# the maximum depth
for it in ptr.child:
maxdepth = max(maxdepth , depthOfTree(it))
return maxdepth + 1
# Function to calculate the diameter
# of the tree
def diameter(ptr):
# Base case
if (not ptr):
return 0
# Find top two highest children
max1, max2 = 0, 0
for it in ptr.child:
h = depthOfTree(it)
if (h > max1):
max2, max1 = max1, h
elif (h > max2):
max2 = h
# Iterate over each child for diameter
maxChildDia = 0
for it in ptr.child:
maxChildDia = max(maxChildDia, diameter(it))
return max(maxChildDia, max1 + max2 + 1)
# Driver program
if __name__ == '__main__':
# /* Let us create below tree
# * A
# * / / \ \
# * B F D E
# * / \ | /|\
# * K J G C H I
# * /\ \
# * N M L
# */
root = Node('A')
(root.child).append(Node('B'))
(root.child).append(Node('F'))
(root.child).append(Node('D'))
(root.child).append(Node('E'))
(root.child[0].child).append(Node('K'))
(root.child[0].child).append(Node('J'))
(root.child[2].child).append(Node('G'))
(root.child[3].child).append(Node('C'))
(root.child[3].child).append(Node('H'))
(root.child[3].child).append(Node('I'))
(root.child[0].child[0].child).append(Node('N'))
(root.child[0].child[0].child).append(Node('M'))
(root.child[3].child[2].child).append(Node('L'))
print(diameter(root))
# This code is contributed by mohit kumar 29
C#
// C# program to find the height of
// an N-ary tree
using System;
using System.Collections.Generic;
class GFG
{
// Structure of a node of an n-ary tree
class Node
{
public char key;
public List<Node> child;
};
// Utility function to create
// a new tree node
static Node newNode(int key)
{
Node temp = new Node();
temp.key = (char) key;
temp.child = new List<Node>();
return temp;
}
// Utility function that will return
// the depth of the tree
static int depthOfTree(Node ptr)
{
// Base case
if (ptr == null)
return 0;
int maxdepth = 0;
// Check for all children and find
// the maximum depth
foreach (Node it in ptr.child)
maxdepth = Math.Max(maxdepth,
depthOfTree(it));
return maxdepth + 1;
}
// Function to calculate the diameter
// of the tree
static int diameter(Node ptr)
{
// Base case
if (ptr == null)
return 0;
// Find top two highest children
int max1 = 0, max2 = 0;
foreach (Node it in ptr.child)
{
int h = depthOfTree(it);
if (h > max1)
{
max2 = max1;
max1 = h;
}
else if (h > max2)
max2 = h;
}
// Iterate over each child for diameter
int maxChildDia = 0;
foreach (Node it in ptr.child)
maxChildDia = Math.Max(maxChildDia,
diameter(it));
return Math.Max(maxChildDia,
max1 + max2 + 1);
}
// Driver Code
public static void Main(String[] args)
{
/* Let us create below tree
* A
* / / \ \
* B F D E
* / \ | /|\
* K J G C H I
* /\ \
* N M L
*/
Node root = newNode('A');
(root.child).Add(newNode('B'));
(root.child).Add(newNode('F'));
(root.child).Add(newNode('D'));
(root.child).Add(newNode('E'));
(root.child[0].child).Add(newNode('K'));
(root.child[0].child).Add(newNode('J'));
(root.child[2].child).Add(newNode('G'));
(root.child[3].child).Add(newNode('C'));
(root.child[3].child).Add(newNode('H'));
(root.child[3].child).Add(newNode('I'));
(root.child[0].child[0].child).Add(newNode('N'));
(root.child[0].child[0].child).Add(newNode('M'));
(root.child[3].child[2].child).Add(newNode('L'));
Console.Write(diameter(root) + "\n");
}
}
// This code is contributed by Rajput-Ji
JavaScript
<script>
// Javascript program to find the
// height of an N-ary tree
// Structure of a node of an n-ary tree
class Node{
// Utility function to create a new tree node
constructor(key)
{
this.key=key;
this.child=[];
}
}
// Utility function that will
// return the depth
// of the tree
function depthOfTree(ptr)
{
// Base case
if (ptr == null)
return 0;
let maxdepth = 0;
// Check for all children and find
// the maximum depth
for (let it=0;it< ptr.child.length;it++)
maxdepth = Math.max(maxdepth,
depthOfTree(ptr.child[it]));
return maxdepth + 1;
}
// Function to calculate the diameter
// of the tree
function diameter(ptr)
{
// Base case
if (ptr == null)
return 0;
// Find top two highest children
let max1 = 0, max2 = 0;
for (let it=0;it< ptr.child.length;it++)
{
let h = depthOfTree(ptr.child[it]);
if (h > max1)
{
max2 = max1;
max1 = h;
}
else if (h > max2)
max2 = h;
}
// Iterate over each child for diameter
let maxChildDia = 0;
for (let it=0;it< ptr.child.length;it++)
maxChildDia = Math.max(maxChildDia,
diameter(ptr.child[it]));
return Math.max(maxChildDia, max1 + max2 + 1);
}
// Driver Code
/* Let us create below tree
* A
* / / \ \
* B F D E
* / \ | /|\
* K J G C H I
* /\ \
* N M L
*/
let root = new Node('A');
(root.child).push(new Node('B'));
(root.child).push(new Node('F'));
(root.child).push(new Node('D'));
(root.child).push(new Node('E'));
(root.child[0].child).push(new Node('K'));
(root.child[0].child).push(new Node('J'));
(root.child[2].child).push(new Node('G'));
(root.child[3].child).push(new Node('C'));
(root.child[3].child).push(new Node('H'));
(root.child[3].child).push(new Node('I'));
(root.child[0].child[0].child).push(new Node('N'));
(root.child[0].child[0].child).push(new Node('M'));
(root.child[3].child[2].child).push(new Node('L'));
document.write(diameter(root) + "\n");
// This code is contributed by patel2127
</script>
- Time Complexity : O( N )
- Space Complexity : O( N )
Optimizations to above solution: We can find diameter without calculating depth of the tree making small changes in the above solution, similar to finding diameter of binary tree.
Implementation:
C++
// C++ program to find the height of an N-ary
// tree
#include <bits/stdc++.h>
using namespace std;
// Structure of a node of an n-ary tree
struct Node
{
char key;
vector<Node *> child;
};
// Utility function to create a new tree node
Node *newNode(int key)
{
Node *temp = new Node;
temp->key = key;
return temp;
}
int diameter(struct Node *ptr,int &diameter_of_tree)
{
// Base case
if (!ptr)
return 0;
// Find top two highest children
int max1 = 0, max2 = 0;
for (vector<Node*>::iterator it = ptr->child.begin();it != ptr->child.end(); it++)
{
int h = diameter(*it,diameter_of_tree);
if (h > max1)
max2 = max1, max1 = h;
else if (h > max2)
max2 = h;
}
// Find whether our node can be part of diameter
diameter_of_tree = max(max1 + max2 + 1,diameter_of_tree);
return max(max1,max2) + 1;
}
int main()
{
/* Let us create below tree
* A
* / / \ \
* B F D E
* / \ / /|\
* K J G C H I
* /\ |
* N M L
*/
Node *root = newNode('A');
(root->child).push_back(newNode('B'));
(root->child).push_back(newNode('F'));
(root->child).push_back(newNode('D'));
(root->child).push_back(newNode('E'));
(root->child[0]->child).push_back(newNode('K'));
(root->child[0]->child).push_back(newNode('J'));
(root->child[2]->child).push_back(newNode('G'));
(root->child[3]->child).push_back(newNode('C'));
(root->child[3]->child).push_back(newNode('H'));
(root->child[3]->child).push_back(newNode('I'));
(root->child[0]->child[0]->child).push_back(newNode('N'));
(root->child[0]->child[0]->child).push_back(newNode('M'));
(root->child[3]->child[2]->child).push_back(newNode('L'));
// for storing diameter
int diameter_of_tree = 0;
diameter(root,diameter_of_tree);
cout << diameter_of_tree << endl;
return 0;
}
// This code is improved by bhuvan
Java
// Java program to find the height of an N-ary
// tree
import java.util.*;
class GFG {
// Structure of a node of an n-ary tree
static class Node {
char key;
Vector<Node> child;
};
// Utility function to create a new tree node
static Node newNode(int key)
{
Node temp = new Node();
temp.key = (char)key;
temp.child = new Vector<Node>();
return temp;
}
// for storing diameter_of_tree
public static int diameter_of_tree = 0;
// Function to calculate the diameter
// of the tree
static int diameter(Node ptr)
{
// Base case
if (ptr == null)
return 0;
// Find top two highest children
int max1 = 0, max2 = 0;
for (Node it : ptr.child) {
int h = diameter(it);
if (h > max1) {
max2 = max1;
max1 = h;
}
else if (h > max2)
max2 = h;
}
diameter_of_tree
= Math.max(max1 + max2 + 1, diameter_of_tree);
return (Math.max(max1, max2) + 1);
}
// Driver Code
public static void main(String[] args)
{
/* Let us create below tree
* A
* / / \ \
* B F D E
* / \ / /|\
* K J G C H I
* /\ |
* N M L
*/
Node root = newNode('A');
(root.child).add(newNode('B'));
(root.child).add(newNode('F'));
(root.child).add(newNode('D'));
(root.child).add(newNode('E'));
(root.child.get(0).child).add(newNode('K'));
(root.child.get(0).child).add(newNode('J'));
(root.child.get(2).child).add(newNode('G'));
(root.child.get(3).child).add(newNode('C'));
(root.child.get(3).child).add(newNode('H'));
(root.child.get(3).child).add(newNode('I'));
(root.child.get(0).child.get(0).child)
.add(newNode('N'));
(root.child.get(0).child.get(0).child)
.add(newNode('M'));
(root.child.get(3).child.get(2).child)
.add(newNode('L'));
diameter(root);
System.out.print(diameter_of_tree + "\n");
}
}
// This code is improved by Bhuvan
Python3
# Python3 program to find the height of an N-ary
# tree
# Structure of a node of an n-ary tree
# Structure of a node of an n-ary tree
class Node:
# Utility function to create a tree node
def __init__(self, key):
self.key = key;
self.child = [];
diameter_of_tree = 0;
def diameter(ptr):
global diameter_of_tree
# Base case
# Base case
if (ptr == None):
return 0;
# Find top two highest children
max1 = 0
max2 = 0;
for it in range(len(ptr.child)):
h = diameter(ptr.child[it]);
if (h > max1):
max2 = max1
max1 = h;
elif (h > max2):
max2 = h;
# Find whether our node can be part of diameter
diameter_of_tree = max(max1 + max2 + 1, diameter_of_tree);
return max(max1,max2) + 1;
def main():
''' us create below tree
* A
* / / \ \
* B F D E
* / \ / /|\
* K J G C H I
* /\ |
* N M L
'''
root = Node('A');
(root.child).append(Node('B'));
(root.child).append(Node('F'));
(root.child).append(Node('D'));
(root.child).append(Node('E'));
(root.child[0].child).append(Node('K'));
(root.child[0].child).append(Node('J'));
(root.child[2].child).append(Node('G'));
(root.child[3].child).append(Node('C'));
(root.child[3].child).append(Node('H'));
(root.child[3].child).append(Node('I'));
(root.child[0].child[0].child).append(Node('N'));
(root.child[0].child[0].child).append(Node('M'));
(root.child[3].child[2].child).append(Node('L'));
diameter(root);
print(diameter_of_tree);
main()
# This code is contributed by phasing17.
C#
// C# program to find the height of an N-ary
// tree
using System;
using System.Collections.Generic;
// Structure of a node of an n-ary tree
class Node {
public char key;
public List<Node> child;
};
class GFG {
// Utility function to create a new tree node
static Node newNode(int key)
{
Node temp = new Node();
temp.key = (char)key;
temp.child = new List<Node>();
return temp;
}
// for storing diameter_of_tree
public static int diameter_of_tree = 0;
// Function to calculate the diameter
// of the tree
static int diameter(Node ptr)
{
// Base case
if (ptr == null)
return 0;
// Find top two highest children
int max1 = 0, max2 = 0;
foreach (Node it in ptr.child) {
int h = diameter(it);
if (h > max1) {
max2 = max1;
max1 = h;
}
else if (h > max2)
max2 = h;
}
diameter_of_tree
= Math.Max(max1 + max2 + 1, diameter_of_tree);
return (Math.Max(max1, max2) + 1);
}
// Driver Code
public static void Main(string[] args)
{
/* Let us create below tree
* A
* / / \ \
* B F D E
* / \ / /|\
* K J G C H I
* /\ |
* N M L
*/
Node root = newNode('A');
(root.child).Add(newNode('B'));
(root.child).Add(newNode('F'));
(root.child).Add(newNode('D'));
(root.child).Add(newNode('E'));
(root.child[0].child).Add(newNode('K'));
(root.child[0].child).Add(newNode('J'));
(root.child[2].child).Add(newNode('G'));
(root.child[3].child).Add(newNode('C'));
(root.child[3].child).Add(newNode('H'));
(root.child[3].child).Add(newNode('I'));
(root.child[0].child[0].child)
.Add(newNode('N'));
(root.child[0].child[0].child)
.Add(newNode('M'));
(root.child[3].child[2].child)
.Add(newNode('L'));
diameter(root);
Console.Write(diameter_of_tree + "\n");
}
}
// This code is improved by phasing17
JavaScript
// Javascript program to find the height of an N-ary
// tree
// Structure of a node of an n-ary tree
// Structure of a node of an n-ary tree
class Node{
// Utility function to create a new tree node
constructor(key)
{
this.key=key;
this.child=[];
}
}
let diameter_of_tree = 0;
function diameter(ptr)
{
// Base case
// Base case
if (ptr == null)
return 0;
// Find top two highest children
let max1 = 0, max2 = 0;
for (let it=0;it< ptr.child.length;it++)
{
let h = diameter(ptr.child[it]);
if (h > max1)
max2 = max1, max1 = h;
else if (h > max2)
max2 = h;
}
// Find whether our node can be part of diameter
diameter_of_tree = Math.max(max1 + max2 + 1,diameter_of_tree);
return Math.max(max1,max2) + 1;
}
/* Let us create below tree
* A
* / / \ \
* B F D E
* / \ / /|\
* K J G C H I
* /\ |
* N M L
*/
let root = new Node('A');
(root.child).push(new Node('B'));
(root.child).push(new Node('F'));
(root.child).push(new Node('D'));
(root.child).push(new Node('E'));
(root.child[0].child).push(new Node('K'));
(root.child[0].child).push(new Node('J'));
(root.child[2].child).push(new Node('G'));
(root.child[3].child).push(new Node('C'));
(root.child[3].child).push(new Node('H'));
(root.child[3].child).push(new Node('I'));
(root.child[0].child[0].child).push(new Node('N'));
(root.child[0].child[0].child).push(new Node('M'));
(root.child[3].child[2].child).push(new Node('L'));
diameter(root,diameter_of_tree);
console.log(diameter_of_tree);
// This code is contributed by garg28harsh.
Output
7
- Time Complexity: O(N^2)
- Auxiliary Space: O(N+H) where N is the number of nodes in tree and H is the height of the tree.
A different optimized solution: Longest path in an undirected tree
Another Approach to get diameter using DFS in one traversal:
The diameter of a tree can be calculated as for every node
- The current node isn't part of diameter (i.e Diameter lies on one of the children of the current node).
- The current node is part of diameter (i.e Diameter passes through the current node).
Node: Adjacency List has been used to store the Tree.
Below is the implementation of the above approach:
C++
// C++ implementation to find
// diameter of a tree using
// DFS in ONE TRAVERSAL
#include <bits/stdc++.h>
using namespace std;
#define maxN 10005
// The array to store the
// height of the nodes
int height[maxN];
// Adjacency List to store
// the tree
vector<int> tree[maxN];
// variable to store diameter
// of the tree
int diameter = 0;
// Function to add edge between
// node u to node v
void addEdge(int u, int v)
{
// add edge from u to v
tree[u].push_back(v);
// add edge from v to u
tree[v].push_back(u);
}
void dfs(int cur, int par)
{
// Variables to store the height of children
// of cur node with maximum heights
int max1 = 0;
int max2 = 0;
// going in the adjacency list of the current node
for (auto u : tree[cur]) {
// if that node equals parent discard it
if (u == par)
continue;
// calling dfs for child node
dfs(u, cur);
// calculating height of nodes
height[cur] = max(height[cur], height[u]);
// getting the height of children
// of cur node with maximum height
if (height[u] >= max1) {
max2 = max1;
max1 = height[u];
}
else if (height[u] > max2) {
max2 = height[u];
}
}
height[cur] += 1;
// Diameter of a tree can be calculated as
// diameter passing through the node
// diameter doesn't includes the cur node
diameter = max(diameter, height[cur]);
diameter = max(diameter, max1 + max2 + 1);
}
// Driver Code
int main()
{
// n is the number of nodes in tree
int n = 7;
// Adding edges to the tree
addEdge(1, 2);
addEdge(1, 3);
addEdge(1, 4);
addEdge(2, 5);
addEdge(4, 6);
addEdge(4, 7);
// Calling the dfs function to
// calculate the diameter of tree
dfs(1, 0);
cout << "Diameter of tree is : " << diameter - 1
<< "\n";
return 0;
}
Java
/*package whatever //do not write package name here */
import java.io.*;
import java.util.*;
class GFG {
static int maxN = 10005;
// The array to store the
// height of the nodes
static int[] height = new int[maxN];
// Adjacency List to store
// the tree
static ArrayList<ArrayList<Integer>> tree = new ArrayList<ArrayList<Integer>>();
// variable to store diameter
// of the tree
static int diameter = 0;
// Function to add edge between
// node u to node v
static void addEdge(int u, int v)
{
// add edge from u to v
tree.get(u).add(v);
// add edge from v to u
tree.get(v).add(u);
}
static void dfs(int cur, int par)
{
// Variables to store the height of children
// of cur node with maximum heights
int max1 = 0;
int max2 = 0;
// going in the adjacency list of the current node
for (int u : tree.get(cur)) {
// if that node equals parent discard it
if (u == par)
continue;
// calling dfs for child node
dfs(u, cur);
// calculating height of nodes
height[cur] = Math.max(height[cur], height[u]);
// getting the height of children
// of cur node with maximum height
if (height[u] >= max1) {
max2 = max1;
max1 = height[u];
}
else if (height[u] > max2) {
max2 = height[u];
}
}
height[cur] += 1;
// Diameter of a tree can be calculated as
// diameter passing through the node
// diameter doesn't includes the cur node
diameter = Math.max(diameter, height[cur]);
diameter = Math.max(diameter, max1 + max2 + 1);
}
public static void main (String[] args)
{
for(int i = 0; i < maxN; i++)
{
tree.add(new ArrayList<Integer>());
}
// n is the number of nodes in tree
int n = 7;
// Adding edges to the tree
addEdge(1, 2);
addEdge(1, 3);
addEdge(1, 4);
addEdge(2, 5);
addEdge(4, 6);
addEdge(4, 7);
// Calling the dfs function to
// calculate the diameter of tree
dfs(1, 0);
System.out.println("Diameter of tree is : " +(diameter - 1));
}
}
// This code is contributed by ab2127.
Python3
# C++ implementation to find
# diameter of a tree using
# DFS in ONE TRAVERSAL
maxN = 10005
# The array to store the
# height of the nodes
height = [0 for i in range(maxN)]
# Adjacency List to store
# the tree
tree = [[] for i in range(maxN)]
# variable to store diameter
# of the tree
diameter = 0
# Function to add edge between
# node u to node v
def addEdge(u, v):
# add edge from u to v
tree[u].append(v)
# add edge from v to u
tree[v].append(u)
def dfs(cur, par):
global diameter
# Variables to store the height of children
# of cur node with maximum heights
max1 = 0
max2 = 0
# going in the adjacency list of the current node
for u in tree[cur]:
# if that node equals parent discard it
if(u == par):
continue
# calling dfs for child node
dfs(u, cur)
# calculating height of nodes
height[cur] = max(height[cur], height[u])
# getting the height of children
# of cur node with maximum height
if(height[u] >= max1):
max2 = max1
max1 = height[u]
elif(height[u] > max2):
max2 = height[u]
height[cur] += 1
# Diameter of a tree can be calculated as
# diameter passing through the node
# diameter doesn't includes the cur node
diameter = max(diameter, height[cur])
diameter = max(diameter, max1 + max2 + 1)
# Driver Code
# n is the number of nodes in tree
n = 7
# Adding edges to the tree
addEdge(1, 2)
addEdge(1, 3)
addEdge(1, 4)
addEdge(2, 5)
addEdge(4, 6)
addEdge(4, 7)
# Calling the dfs function to
# calculate the diameter of tree
dfs(1, 0)
print("Diameter of tree is :", diameter - 1)
# This code is contributed by avanitrachhadiya2155
C#
using System;
using System.Collections.Generic;
class GFG {
static int maxN = 10005;
// The array to store the
// height of the nodes
static int[] height = new int[maxN];
// Adjacency List to store
// the tree
static List<List<int>> tree = new List<List<int>>();
// variable to store diameter
// of the tree
static int diameter = 0;
// Function to Add edge between
// node u to node v
static void AddEdge(int u, int v)
{
// Add edge from u to v
tree[u].Add(v);
// Add edge from v to u
tree[v].Add(u);
}
static void dfs(int cur, int par)
{
// Variables to store the height of children
// of cur node with maximum heights
int max1 = 0;
int max2 = 0;
// going in the adjacency list of the current node
foreach (int u in tree[cur]) {
// if that node equals parent discard it
if (u == par)
continue;
// calling dfs for child node
dfs(u, cur);
// calculating height of nodes
height[cur] = Math.Max(height[cur], height[u]);
// getting the height of children
// of cur node with maximum height
if (height[u] >= max1) {
max2 = max1;
max1 = height[u];
}
else if (height[u] > max2) {
max2 = height[u];
}
}
height[cur] += 1;
// Diameter of a tree can be calculated as
// diameter passing through the node
// diameter doesn't includes the cur node
diameter = Math.Max(diameter, height[cur]);
diameter = Math.Max(diameter, max1 + max2 + 1);
}
public static void Main (string[] args)
{
for(int i = 0; i < maxN; i++)
{
tree.Add(new List<int>());
}
// n is the number of nodes in tree
int n = 7;
// Adding edges to the tree
AddEdge(1, 2);
AddEdge(1, 3);
AddEdge(1, 4);
AddEdge(2, 5);
AddEdge(4, 6);
AddEdge(4, 7);
// Calling the dfs function to
// calculate the diameter of tree
dfs(1, 0);
Console.WriteLine("Diameter of tree is : " +(diameter - 1));
}
}
// This code is contributed by phasing17.
JavaScript
<script>
// Javascript implementation to find
// diameter of a tree using
// DFS in ONE TRAVERSAL
let maxN = 10005;
// The array to store the
// height of the nodes
let height=new Array(maxN);
// Adjacency List to store
// the tree
let tree=new Array(maxN);
for(let i=0;i<maxN;i++)
{
height[i]=0;
tree[i]=[];
}
// variable to store diameter
// of the tree
let diameter = 0;
// Function to add edge between
// node u to node v
function addEdge(u,v)
{
// add edge from u to v
tree[u].push(v);
// add edge from v to u
tree[v].push(u);
}
function dfs(cur,par)
{
// Variables to store the height of children
// of cur node with maximum heights
let max1 = 0;
let max2 = 0;
// going in the adjacency list
// of the current node
for (let u=0;u<tree[cur].length;u++) {
// if that node equals parent discard it
if (tree[cur][u] == par)
continue;
// calling dfs for child node
dfs(tree[cur][u], cur);
// calculating height of nodes
height[cur] = Math.max(height[cur],
height[tree[cur][u]]);
// getting the height of children
// of cur node with maximum height
if (height[tree[cur][u]] >= max1) {
max2 = max1;
max1 = height[tree[cur][u]];
}
else if (height[tree[cur][u]] > max2) {
max2 = height[tree[cur][u]];
}
}
height[cur] += 1;
// Diameter of a tree can be calculated as
// diameter passing through the node
// diameter doesn't includes the cur node
diameter = Math.max(diameter, height[cur]);
diameter = Math.max(diameter, max1 + max2 + 1);
}
// Driver Code
// n is the number of nodes in tree
let n = 7;
// Adding edges to the tree
addEdge(1, 2);
addEdge(1, 3);
addEdge(1, 4);
addEdge(2, 5);
addEdge(4, 6);
addEdge(4, 7);
// Calling the dfs function to
// calculate the diameter of tree
dfs(1, 0);
document.write("Diameter of tree is : " +(diameter - 1))
// This code is contributed by unknown2108
</script>
- Time Complexity: O(N), Where N is the number of nodes in given binary tree.
- Auxiliary Space: O(N)
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 Traversals
Inorder 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 Tree
Check 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