AlgoMaster Logo

Diameter of Binary Tree

Ashish

Ashish Pratap Singh

easy

Problem Description

Solve it on LeetCode

Approaches

1. Recursive Approach

The naive idea here is to consider each node of the binary tree, calculate the maximum path length traversing through it, and then take the largest of these lengths. The maximum path of a node is calculated as the sum of the heights of its left and right subtrees.

Intuition:

  1. Definition of Diameter: For every node we consider, its diameter is defined as the number of nodes on the longest path between two leaves.
  2. Height Calculation: The height of a node in this approach is determined by calculating the height of its left and right subtrees recursively.
  3. Brute Force Calculation: For each node, calculate the diameter (left height + right height), and update the maximum diameter found so far.

Code:

2. Optimized Recursive Approach

To optimize the naive approach, we can calculate the height of the tree while computing the diameter at the same time. This prevents re-calculation of the height, reducing redundant operations.

Intuition:

  1. Postorder Traversal: Utilize postorder traversal, where we calculate the height of subtrees and the diameter while backtracking.
  2. Passing the Max Diameter: Use a global or wrapper object to store the maximum diameter found during the traversal.

Code: