Diameter of a tree using DFS

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 diameter 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 below post

Diameter of a binary tree



In this post a different DFS based solution is discussed. After observing 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 adjacency list representation of graphs. STL‘s list container is used to store lists of adjacent nodes.

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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;
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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

chevron_right



Output:

Diameter of the given tree is 4

This article is contributed by Ankur Singh. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.



My Personal Notes arrow_drop_up