GeeksforGeeks App
Open App
Browser
Continue

# 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 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)

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 ``#include ``#include ``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 adj[];``    ` `    ``// Sets maxCount as maximum distance``    ``// from node``    ``static` `void` `dfsUtil(``int` `node, ``int` `count,``                         ``boolean` `visited[],``                       ``List adj[])``    ``{``        ``visited[node] = ``true``;``        ``count++;``        ` `        ``List 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``                                       ``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 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();``     ` `        ``/*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

 ``

Output

`Diameter of the given tree is 4`

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

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

My Personal Notes arrow_drop_up