Diameter of Binary Tree - aloalgo

Diameter of Binary Tree

Medium

You are given the root of a binary tree.

Your task is to determine the diameter of the tree.

You may assume that:

  • The diameter of a binary tree is defined as the length of the longest path between any two nodes in the tree.
  • This path may or may not pass through the root.
  • The length of a path between two nodes is represented by the number of edges between them.
  • An empty tree has a diameter of 0.

Return an integer representing the diameter of the tree.

Example 1

Input
12453
Output
3
Explanation:

The longest path is between nodes 4 and 5, passing through node 2. This path has 3 edges (4-2, 2-5). The path between 4 and 3 (passing through 2 and 1) has 4 edges (4-2, 2-1, 1-3). However, the definition of diameter is the longest path between any two nodes. In this specific example, the longest path is between node 4 and node 3, or node 5 and node 3. The path between 4 and 3 is 4-2-1-3, length 3. The diameter of the tree is 3 (e.g., path from 4 to 5, length 3). If the path was 4-2-1-3, the length would be 3. The example image is correct, but my manual calculation seems off. Let me correct the explanation based on the definition of diameter often used in problems like these: it's the maximum number of edges between any two nodes. For [1,2,3,4,5], the longest path is from node 4 to node 5, passing through node 2, with 3 edges.

Example 2

Input
12
Output
1
Explanation:

The only path is between node 1 and node 2, with 1 edge.

Example 3

Input
1
Output
0
Explanation:

The tree has only one node. There are no two distinct nodes to form a path, so the diameter is 0.

Loading...
Input
12453
Output
3

Hello! I am your ✨ AI assistant. I can provide you hints, explanations, give feedback on your code, and more. Just ask me anything related to the problem you're working on!