4. Diameter of a Binary Tree

The problem can be found at the following link: Problem Link

Problem Description

Given a binary tree, the diameter (or width) is defined as the number of edges on the longest path between two leaf nodes in the tree. This path may or may not pass through the root. Your task is to determine the diameter of the tree.

Examples

Input: root[] = [1, 2, 3]

Output: 2 Explanation: The longest path has 2 edges: (node 2 -> node 1 -> node 3).

Input: root[] = [5, 8, 6, 3, 7, 9]

Output: 4 Explanation: The longest path has 4 edges: (node 3 -> node 8 -> node 5 -> node 6 -> node 9).

Constraints

  • 1 ≤ number of nodes ≤ $10^5$

  • 0 ≤ node->data ≤ $10^5$

My Approach

  1. Single DFS Traversal (Pair Method): Use a recursive function that returns a pair: the height of the current subtree and the diameter computed so far. For each node, compute:

    • The height as 1 + max(height(left), height(right)).

    • The diameter as the maximum of:

      • The diameter in the left subtree.

      • The diameter in the right subtree.

      • The sum of the heights of the left and right subtrees (which represents the path passing through the current node).

Time and Auxiliary Space Complexity

  • Expected Time Complexity: O(N), as each node is visited exactly once.

  • Expected Auxiliary Space Complexity: O(H), where H is the height of the tree (due to recursion stack).

Code (C)

Code (C++)

🌲 Alternative Approaches

1️⃣ Using a Pair (Single DFS Traversal)

2️⃣ Iterative Approach (BFS + Map for Height)

3️⃣ Two-Pass DFS (Undirected Graph Approach)

Comparison of Approaches

Approach
Time Complexity
Space Complexity
Method
Pros
Cons

Pair (Single DFS)

🟢 O(N)

🟡 O(H)

DFS

Concise, single-pass

Recursion may be deep

Iterative BFS + Map

🟢 O(N)

🔴 O(N)

Iterative

Avoids recursion depth issues

Extra space for map/vector

Two-Pass DFS (Undirected)

🟢 O(N)

🔴 O(N)

DFS

Finds true farthest nodes

Requires building an adjacency list

Best Choice?

  • Use the Pair (Single DFS) for clarity if recursion depth is acceptable.

  • The Iterative BFS is preferable when avoiding recursion is important.

  • The Two-Pass DFS method is ideal when you need the undirected perspective to correctly capture all paths.

Code (Java)

Code (Python)

Contribution and Support

For discussions, questions, or doubts related to this solution, feel free to connect on LinkedIn: Any Questions. Let’s make this learning journey more collaborative!

⭐ If you find this helpful, please give this repository a star! ⭐


📍Visitor Count

Last updated