The Wayback Machine - https://web.archive.org/web/20240915203104/https://www.geeksforgeeks.org/diameter-tree-using-dfs/
Open In App

Diameter of a tree using DFS

Last Updated : 15 Jul, 2022
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow
Companies:
Show Topics
Solve Problem
Medium
47.37%
2.9L

The diameter of a tree (sometimes called the width) is the number of nodes on the longest path between two leaves in the tree. The diagram below shows two trees each with a diameter of five, the leaves that form the ends of the longest path are shaded (note that there is more than one path in each tree of length five, but no path longer than five nodes) 

Diameter, 5 nodes through root

We have discussed a solution in the below post
Diameter of a binary tree
In this post, a different DFS-based solution is discussed. After observing the above tree we can see that the longest path will always occur between two leaf nodes. We start DFS from a random node and then see which node is farthest from it. Let the node farthest be X. It is clear that X will always be a leaf node and a corner of DFS. Now if we start DFS from X and check the farthest node from it, we will get the diameter of the tree. 
The C++ implementation uses an adjacency list representation of graphs. STL‘s list container is used to store lists of adjacent nodes. 

Implementation:

C++




// C++ program to find diameter of a binary tree
// using DFS.
#include <iostream>
#include <limits.h>
#include <list>
using namespace std;
 
// Used to track farthest node.
int x;
 
// Sets maxCount as maximum distance from node.
void dfsUtil(int node, int count, bool visited[],
                   int& maxCount, list<int>* adj)
{
    visited[node] = true;
    count++;
    for (auto i = adj[node].begin(); i != adj[node].end(); ++i) {
        if (!visited[*i]) {
            if (count >= maxCount) {
                maxCount = count;
                x = *i;
            }
            dfsUtil(*i, count, visited, maxCount, adj);
        }
    }
}
 
// The function to do DFS traversal. It uses recursive
// dfsUtil()
void dfs(int node, int n, list<int>* adj, int& maxCount)
{
    bool visited[n + 1];
    int count = 0;
 
    // Mark all the vertices as not visited
    for (int i = 1; i <= n; ++i)
        visited[i] = false;
 
    // Increment count by 1 for visited node
    dfsUtil(node, count + 1, visited, maxCount, adj);
}
 
// Returns diameter of binary tree represented
// as adjacency list.
int diameter(list<int>* adj, int n)
{
    int maxCount = INT_MIN;
 
    /* DFS from a random node and then see
    farthest node X from it*/
    dfs(1, n, adj, maxCount);
 
    /* DFS from X and check the farthest node
    from it */
    dfs(x, n, adj, maxCount);
 
    return maxCount;
}
 
/* Driver program to test above functions*/
int main()
{
    int n = 5;
 
    /* Constructed tree is
         1
        / \
        2    3
       / \
      4   5 */
    list<int>* adj = new list<int>[n + 1];
 
    /*create undirected edges */
    adj[1].push_back(2);
    adj[2].push_back(1);
    adj[1].push_back(3);
    adj[3].push_back(1);
    adj[2].push_back(4);
    adj[4].push_back(2);
    adj[2].push_back(5);
    adj[5].push_back(2);
 
 
    /* maxCount will have diameter of tree */
    cout << "Diameter of the given tree is "
        << diameter(adj, n) << endl;
    return 0;
}


Java




// Java program to find diameter of a
// binary tree using DFS.
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class Diametre_tree {
  
    // Used to track farthest node.
    static int x;
    static int maxCount;
    static List<Integer> adj[];
     
    // Sets maxCount as maximum distance
    // from node
    static void dfsUtil(int node, int count,
                         boolean visited[],
                       List<Integer> adj[])
    {
        visited[node] = true;
        count++;
         
        List<Integer> l = adj[node];
        for(Integer i: l)
        {
            if(!visited[i]){
                if (count >= maxCount) {
                    maxCount = count;
                    x = i;
                }
                dfsUtil(i, count, visited, adj);
            }
        }
    }
      
    // The function to do DFS traversal. It uses
    // recursive dfsUtil()
    static void dfs(int node, int n, List<Integer>
                                       adj[])
    {
        boolean[] visited = new boolean[n + 1];
        int count = 0;
      
        // Mark all the vertices as not visited
        Arrays.fill(visited, false);
      
        // Increment count by 1 for visited node
        dfsUtil(node, count + 1, visited, adj);
         
    }
      
    // Returns diameter of binary tree represented
    // as adjacency list.
    static int diameter(List<Integer> adj[], int n)
    {
        maxCount = Integer.MIN_VALUE;
      
        /* DFS from a random node and then see
        farthest node X from it*/
        dfs(1, n, adj);
      
        /* DFS from X and check the farthest node
        from it */
        dfs(x, n, adj);
      
        return maxCount;
    }
      
    /* Driver program to test above functions*/
    public static void main(String args[])
    {
        int n = 5;
      
        /* Constructed tree is
             1
            / \
            2    3
           / \
          4   5 */
        adj = new List[n + 1];
        for(int i = 0; i < n+1 ; i++)
            adj[i] = new ArrayList<Integer>();
      
        /*create undirected edges */
        adj[1].add(2);
        adj[2].add(1);
        adj[1].add(3);
        adj[3].add(1);
        adj[2].add(4);
        adj[4].add(2);
        adj[2].add(5);
        adj[5].add(2);
         
        /* maxCount will have diameter of tree */
        System.out.println("Diameter of the given " +
                       "tree is " + diameter(adj, n));
    }
}
// This code is contributed by Sumit Ghosh


Python3




# Python3 program to find diameter of a binary tree
# using DFS.
 
# Sets maxCount as maximum distance from node.
def dfsUtil(node, count):
    global visited, x, maxCount, adj
    visited[node] = 1
    count += 1
    for i in adj[node]:
        if (visited[i] == 0):
            if (count >= maxCount):
                maxCount = count
                x = i
            dfsUtil(i, count)
 
# The function to do DFS traversal. It uses recursive
# dfsUtil()
def dfs(node, n):
    count = 0
    for i in range(n + 1):
        visited[i] = 0
 
    # Increment count by 1 for visited node
    dfsUtil(node, count + 1)
 
# Returns diameter of binary tree represented
# as adjacency list.
def diameter(n):
    global adj, maxCount
 
    # DFS from a random node and then see
    # farthest node X from it*/
    dfs(1, n)
 
    # DFS from X and check the farthest node
    dfs(x, n)
    return maxCount
 
## Driver code*/
if __name__ == '__main__':
    n = 5
 
    # # Constructed tree is
    #      1
    #     / \
    #     2    3
    #    / \
    #   4   5 */
    adj, visited = [[] for i in range(n + 1)], [0 for i in range(n + 1)]
    maxCount = -10**19
    x = 0
 
    # create undirected edges */
    adj[1].append(2)
    adj[2].append(1)
    adj[1].append(3)
    adj[3].append(1)
    adj[2].append(4)
    adj[4].append(2)
    adj[2].append(5)
    adj[5].append(2)
 
    # maxCount will have diameter of tree */
    print ("Diameter of the given tree is ", diameter(n))
 
    # This code is contributed by mohit kumar 29


C#




// C# program to find diameter of a
// binary tree using DFS.
using System;
using System.Collections.Generic;
 
class GFG
{
 
    // Used to track farthest node.
    static int x;
    static int maxCount;
    static List<int> []adj;
     
    // Sets maxCount as maximum distance
    // from node
    static void dfsUtil(int node, int count,
                             bool []visited,
                            List<int> []adj)
    {
        visited[node] = true;
        count++;
         
        List<int> l = adj[node];
        foreach(int i in l)
        {
            if(!visited[i])
            {
                if (count >= maxCount)
                {
                    maxCount = count;
                    x = i;
                }
                dfsUtil(i, count, visited, adj);
            }
        }
    }
     
    // The function to do DFS traversal. It uses
    // recursive dfsUtil()
    static void dfs(int node, int n,
                    List<int> []adj)
    {
        bool[] visited = new bool[n + 1];
        int count = 0;
 
     
        // Increment count by 1 for visited node
        dfsUtil(node, count + 1, visited, adj);
    }
     
    // Returns diameter of binary tree represented
    // as adjacency list.
    static int diameter(List<int> []adj, int n)
    {
        maxCount = int.MinValue;
     
        /* DFS from a random node and then see
        farthest node X from it*/
        dfs(1, n, adj);
     
        /* DFS from X and check the farthest node
        from it */
        dfs(x, n, adj);
     
        return maxCount;
    }
     
    // Driver Code
    public static void Main(String []args)
    {
        int n = 5;
     
        /* Constructed tree is
            1
            / \
            2 3
        / \
        4 5 */
        adj = new List<int>[n + 1];
        for(int i = 0; i < n + 1; i++)
            adj[i] = new List<int>();
     
        /*create undirected edges */
        adj[1].Add(2);
        adj[2].Add(1);
        adj[1].Add(3);
        adj[3].Add(1);
        adj[2].Add(4);
        adj[4].Add(2);
        adj[2].Add(5);
        adj[5].Add(2);
         
        /* maxCount will have diameter of tree */
        Console.WriteLine("Diameter of the given " +
                     "tree is " + diameter(adj, n));
    }
}
 
// This code is contributed by PrinciRaj1992


Javascript




<script>
 
// JavaScript program to find diameter of a
// binary tree using DFS.
     
    // Used to track farthest node.
    let x;
    let maxCount;
    let adj=[];
     
    // Sets maxCount as maximum distance
    // from node
    function dfsUtil(node,count,visited,adj)
    {
        visited[node] = true;
        count++;
          
        let l = adj[node];
        for(let i=0;i<l.length;i++)
        {
            if(!visited[l[i]]){
                if (count >= maxCount) {
                    maxCount = count;
                    x = l[i];
                }
                dfsUtil(l[i], count, visited, adj);
            }
        }
    }
     
    // The function to do DFS traversal. It uses
    // recursive dfsUtil()
    function dfs(node,n,adj)
    {
        let visited = new Array(n + 1);
        let count = 0;
       
        // Mark all the vertices as not visited
        for(let i=0;i<visited.length;i++)
        {
            visited[i]=false;
        }
       
        // Increment count by 1 for visited node
        dfsUtil(node, count + 1, visited, adj);
    }
     
    // Returns diameter of binary tree represented
    // as adjacency list.
    function diameter(adj,n)
    {
        maxCount = Number.MIN_VALUE;
       
        /* DFS from a random node and then see
        farthest node X from it*/
        dfs(1, n, adj);
       
        /* DFS from X and check the farthest node
        from it */
        dfs(x, n, adj);
       
        return maxCount;
    }
     
    /* Driver program to test above functions*/
    let n = 5;
    /* Constructed tree is
             1
            / \
            2    3
           / \
          4   5 */
        adj = new Array(n + 1);
        for(let i = 0; i < n+1 ; i++)
            adj[i] = [];
       
        /*create undirected edges */
        adj[1].push(2);
        adj[2].push(1);
        adj[1].push(3);
        adj[3].push(1);
        adj[2].push(4);
        adj[4].push(2);
        adj[2].push(5);
        adj[5].push(2);
          
        /* maxCount will have diameter of tree */
        document.write("Diameter of the given " +
                       "tree is " + diameter(adj, n));
     
 
 
// This code is contributed by unknown2108
 
</script>


Output

Diameter of the given tree is 4

Time Complexity: O(n), where n is the number of nodes
Auxiliary Space: O(n)

 



Similar Reads

Diameter of n-ary tree using BFS
N-ary tree refers to the rooted tree in which each node having atmost k child nodes. The diameter of n-ary tree is the longest path between two leaf nodes. Various approaches have already been discussed to compute diameter of tree. Diameter of an N-ary tree Diameter of a Binary Tree in O(n) Diameter of a Binary Tree Diameter of a tree using DFS Thi
7 min read
Possible edges of a tree for given diameter, height and vertices
Find a tree with the given values and print the edges of the tree. Print "-1", if the tree is not possible. Given three integers n, d and h. n -&gt; Number of vertices. [1, n] d -&gt; Diameter of the tree (largest distance between two vertices). h -&gt; Height of the tree (longest distance between vertex 1 and another vertex) Examples : Input : n =
8 min read
DP on Trees | Set-3 ( Diameter of N-ary Tree )
Given an N-ary tree T of N nodes, the task is to calculate the longest path between any two nodes(also known as the diameter of the tree). Example 1: Example 2: Different approaches to solving these problems have already been discussed: https://www.geeksforgeeks.org/diameter-n-ary-tree/https://www.geeksforgeeks.org/diameter-n-ary-tree-using-bfs/ In
9 min read
Make a tree with n vertices , d diameter and at most vertex degree k
Given three integers N, D and K. The task is to check whether it is possible to make a tree with exactly N vertices, D diameter (the number of edges in the longest path between any two vertices), and degree of each vertex must be at most K. If it is possible then print all the possible edges otherwise print No. Examples: Input: N = 6, D = 3, K = 4
11 min read
Diameter of a Binary Indexed Tree with N nodes
Given a Binary Indexed Tree with N nodes except root node 0 (Numbered from 1 to N), Find its diameter. Binary Indexed Tree is a tree where parent of a node number X = X - (X &amp; (X - 1)) i.e. last bit is unset in X. The diameter of a tree is the longest simple path between any two leaves. Examples: Input: N = 12 Output: 6 Explanation: Path from n
7 min read
Finding the lexicographically smallest diameter in a binary tree
Given a binary tree where node values are lowercase alphabets, the task is to find the lexicographically smallest diameter. Diameter is the longest path between any two leaf nodes, hence, there can be multiple diameters in a Binary Tree. The task is to print the lexicographically smallest diameter among all possible diameters.Examples: Input: a / \
13 min read
CSES Solutions - Tree Diameter
You are given a tree consisting of n nodes. The diameter of a tree is the maximum distance between two nodes. Your task is to determine the diameter of the tree. Examples: Input: n = 5, edges = { { 1, 2 }, { 1, 3 }, { 3, 4 }, { 3, 5 } };Output: 3 Input: n = 4, edges = { { 1, 2 }, { 1, 3 }, { 3, 4 }};Output: 3 Approach: We can uses a Depth-First Sea
6 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 the nodes and go up to one of the LCAs of these node
15+ min read
Diameter of a Binary Tree in O(n) [A new method]
The diameter of a tree is the number of nodes on the longest path between two leaves in the tree. The diagram below shows two trees each with diameter nine, the leaves that form the ends of the longest path are colored (note that there may be more than one path in the tree of the same diameter).  Examples:  Input : 1 / \ 2 3 / \ 4 5Output : 4Input
6 min read
Diameter of a Binary Tree
The diameter/width of a tree is defined as the number of nodes on the longest path between any two nodes.  The diagram below shows two trees each with a diameter of nine, the leaves that form the ends of the longest path are shaded (note that there is more than one path in each tree of length nine, but no path longer than nine nodes).  Naive Approa
15+ min read
Subtree of all nodes in a tree using DFS
Given n nodes of a tree and their connections, print Subtree nodes of every node.Subtree of a node is defined as a tree which is a child of a node. The name emphasizes that everything which is a descendant of a tree node is a tree too, and is a subset of the larger tree. Examples : Input: N = 5 0 1 1 2 0 3 3 4 Output: Subtree of node 0 is 1 2 3 4 S
8 min read
Level with maximum number of nodes using DFS in a N-ary tree
Given a N-ary tree, the task is to print the level with the maximum number of nodes. Examples: Input : For example, consider the following tree 1 - Level 1 / \ 2 3 - Level 2 / \ \ 4 5 6 - Level 3 / \ / 7 8 9 - Level 4 Output : Level-3 and Level-4 Approach: Insert all the connecting nodes to a 2-D vector tree.Run a DFS on the tree such that height[n
10 min read
Construct the Rooted tree by using start and finish time of its DFS traversal
Given start and finish times of DFS traversal of N vertices that are available in a Rooted tree, the task is to construct the tree (Print the Parent of each node). Parent of the root node is 0.Examples: Input: Start[] = {2, 4, 1, 0, 3}, End[] = {3, 5, 4, 5, 4} Output: 3 4 4 0 3 Given Tree is -: 4(0, 5) / \ (1, 4)3 2(4, 5) / \ (2, 3)1 5(3, 4) The ro
8 min read
Count the number of nodes at a given level in a tree using DFS
Given an integer l and a tree represented as an undirected graph rooted at vertex 0. The task is to print the number of nodes present at level l. Examples:  Input: l = 2   Output: 4  We have already discussed the BFS approach, in this post we will solve it using DFS. Approach: The idea is to traverse the graph in a DFS manner. Take two variables, c
8 min read
Find the center of the circle using endpoints of diameter
Given two endpoint of diameter of a circle (x1, y1) and (x2, y2) find out the center of a circle. Examples : Input : x1 = -9, y1 = 3, and x2 = 5, y2 = –7 Output : -2, –2 Input : x1 = 5, y1 = 3 and x2 = –10 y2 = 4 Output : –2.5, 3.5 Midpoint Formula: The midpoint of two points, (x1, y2) and (x2, y2) is : M = ((x 1 + x 2) / 2, (y 1 + y 2) / 2) The ce
4 min read
Queries for DFS of a subtree in a tree
Given a tree of N nodes and N-1 edges. The task is to print the DFS of the subtree of a given node for multiple queries. The DFS must include the given node as the root of the subtree. In the above tree, if 1 is given as the node, then the DFS of subtree will be 1 2 4 6 7 5 3.If 2 is given as the node, then the DFS of the subtree will be 2 4 6 7 5.
11 min read
Tree, Back, Edge and Cross Edges in DFS of Graph
Consider a directed graph given in below, DFS of the below graph is 1 2 4 6 3 5 7 8. In below diagram if DFS is applied on this graph a tree is obtained which is connected using green edges. Tree Edge: It is an edge which is present in the tree obtained after applying DFS on the graph. All the Green edges are tree edges. Forward Edge: It is an edge
11 min read
Find the Kth node in the DFS traversal of a given subtree in a Tree
Given a tree with N nodes, and two integers K and V. The task is to find the Kth node in the DFS traversal of the vertex V.Consider the below Tree: DFS of node number 1 is [1, 2, 3, 5, 6, 8, 7, 9, 4]. DFS of node number 3 is [3, 5, 6, 8, 7, 9] DFS of node number 7 is [7, 9] DFS of node number 9 is [9]. Print "-1" if the numbers in the DFS of vertex
10 min read
DFS for a n-ary tree (acyclic graph) represented as adjacency list
A tree consisting of n nodes is given, we need to print its DFS. Examples : Input : Edges of graph 1 2 1 3 2 4 3 5 Output : 1 2 4 3 5 A simple solution is to do implement standard DFS. We can modify our approach to avoid extra space for visited nodes. Instead of using the visited array, we can keep track of parent. We traverse all adjacent nodes bu
4 min read
DFS traversal of a Tree
Given a Binary tree, Traverse it using DFS using recursion. Unlike linear data structures (Array, Linked List, Queues, Stacks, etc) which have only one logical way to traverse them, trees can be traversed in different ways. Generally, there are 2 widely used ways for traversing trees: DFS or Depth-First SearchBFS or Breadth-First Search What is a D
15+ min read
BFS vs DFS for Binary Tree
Breadth-First Search (BFS) and Depth-First Search (DFS) for Binary Trees are ways to traverse nodes of the Binary Tree. This article aims to provide the basic difference between BFS and DFS for Binary Tree. A Tree is typically traversed in two ways:Breadth First Traversal (Or Level Order Traversal)Depth First TraversalsInorder Traversal (Left-Root-
3 min read
Find minimum Diameter BST having Sum equal to target K
Given a binary tree and a target K, the task is to find the diameter of the minimum subtree having sum equal to K which is also a binary search tree. Return -1 if not possible. Examples: Input: K = 38 13 / \ 5 23 / \ / \ N 17 N N / \ 16 NOutput: 3Explanation: 5, 17, 16 is the smallest subtree with diameter 3. Input: K = 73 7 / \ N 23 / \ 10 23 / \
11 min read
Find the other-end coordinates of diameter in a circle
Given Centre coordinate (c1, c2) and one coordinate (x1, y1) of the diameter of a circle, find the other end coordinate point (x2, y2) of diameter. Examples: Input : x1 = –1, y1 = 2, and c1 = 3, c2 = –6 Output : x2 = 7, y2 = -14 Input : x1 = 6.4, y1 = 3 and c1 = –10.7, c2 = 4 Output : x2 = -27.8, y2 = 5 The Midpoint Formula: The midpoint of two end
5 min read
Program to find the diameter, cycles and edges of a Wheel Graph
Wheel Graph: A Wheel graph is a graph formed by connecting a single universal vertex to all vertices of a cycle. Properties: Wheel graphs are Planar graphs.There is always a Hamiltonian cycle in the Wheel graph.Chromatic Number is 3 and 4, if n is odd and even respectively. Problem Statement: Given the Number of Vertices in a Wheel Graph. The task
7 min read
Find the Diameter or Longest chord of a Circle
Given a circle with radius 'r' is given, the task is to find the diameter or longest chord of the circle.Examples: Input: r = 4 Output: 8 Input: r = 9 Output: 18 Proof that the Longest chord of a circle is its Diameter: Draw circle O and any chord AB on it.From one endpoint of the chord, say A, draw a line segment through the centre. That is, draw
4 min read
Length of the chord the circle if length of the another chord which is equally inclined through the diameter is given
Given are two chords which are equally inclined through the diameter of the circle. Length of one chord is given. The task is to find the length of another chord.Examples: Input: z = 48 Output: 48 degrees Input: z = 93 Output: 93 degrees Approach: Let AB and AC be the two chords of the circle having the center at O.now, in the figure we see, OL is
3 min read
Check if a graph is strongly connected | Set 1 (Kosaraju using DFS)
Given a directed graph, find out whether the graph is strongly connected or not. A directed graph is strongly connected if there is a path between any two pair of vertices. For example, following is a strongly connected graph. It is easy for undirected graph, we can just do a BFS and DFS starting from any vertex. If BFS or DFS visits all vertices,
13 min read
Check if a given graph is Bipartite using DFS
Given a connected graph, check if the graph is bipartite or not. A bipartite graph is possible if the graph coloring is possible using two colors such that vertices in a set are colored with the same color. Note that it is possible to color a cycle graph with an even cycle using two colors. For example, see the following graph. It is not possible t
9 min read
Minimum number of edges between two vertices of a graph using DFS
Given an undirected graph G(V, E) with N vertices and M edges. We need to find the minimum number of edges between a given pair of vertices (u, v). We have already discussed this problem using the BFS approach, here we will use the DFS approach. Examples: Input: For the following given graph, find the minimum number of edges between vertex pair (0,
10 min read
Implementation of DFS using adjacency matrix
Depth First Search (DFS) has been discussed in this article which uses adjacency list for the graph representation. In this article, adjacency matrix will be used to represent the graph.Adjacency matrix representation: In adjacency matrix representation of a graph, the matrix mat[][] of size n*n (where n is the number of vertices) will represent th
8 min read