LeetCode 1245. Tree Diameter Solution in Java, C++, Python & More | Explanation + Code

CoderIndeed
0
1245. Tree Diameter

Description

The diameter of a tree is the number of edges in the longest path in that tree.

There is an undirected tree of n nodes labeled from 0 to n - 1. You are given a 2D array edges where edges.length == n - 1 and edges[i] = [ai, bi] indicates that there is an undirected edge between nodes ai and bi in the tree.

Return the diameter of the tree.

 

Example 1:

Input: edges = [[0,1],[0,2]]
Output: 2
Explanation: The longest path of the tree is the path 1 - 0 - 2.

Example 2:

Input: edges = [[0,1],[1,2],[2,3],[1,4],[4,5]]
Output: 4
Explanation: The longest path of the tree is the path 3 - 2 - 1 - 4 - 5.

 

Constraints:

  • n == edges.length + 1
  • 1 <= n <= 104
  • 0 <= ai, bi < n
  • ai != bi

Solutions

Solution 1: Two DFS Passes

First, we arbitrarily select a node and start a depth-first search (DFS) from this node to find the farthest node from it, denoted as node a. Then, we start another DFS from node a to find the farthest node from node a, denoted as node b. It can be proven that the path between node a and node b is the diameter of the tree.

Time complexity is O(n), and space complexity is O(n), where n is the number of nodes.

Similar problems:

PythonJavaC++GoTypeScript
class Solution: def treeDiameter(self, edges: List[List[int]]) -> int: def dfs(i: int, fa: int, t: int): for j in g[i]: if j != fa: dfs(j, i, t + 1) nonlocal ans, a if ans < t: ans = t a = i g = defaultdict(list) for a, b in edges: g[a].append(b) g[b].append(a) ans = a = 0 dfs(0, -1, 0) dfs(a, -1, 0) return ans(code-box)

Post a Comment

0Comments

Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Check Now
Accept !