Tutorialspoint
Problem
Solution
Submissions

Diameter of Binary Tree

Certification: Basic Level Accuracy: 0% Submissions: 0 Points: 5

Write a C program to find the diameter of a binary tree. The diameter of a binary tree is the length of the longest path between any two nodes in a 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.

Example 1
  • Input:

    Binary Tree with Diameter 3


  • Output: 3
  • Explanation:
    • Step 1: The longest path is between nodes 4 and 3, which passes through nodes 2 and 1
    • Step 2: The path 4 -> 2 -> 1 -> 3 has 3 edges
    • Step 3: Therefore, the diameter of this binary tree is 3
Example 2
  • Input:

    Binary Tree with Diameter 4

  • Output: 4
  • Explanation:
    • Step 1: The longest path is between nodes 5 and 3, which passes through nodes 4, 2, and 1
    • Step 2: The path 5 -> 4 -> 2 -> 1 -> 3 has 4 edges
    • Step 3: Therefore, the diameter of this binary tree is 4
Constraints
  • The number of nodes in the tree is in the range [1, 10^4]
  • -100 ≤ Node.val ≤ 100
  • The diameter might not pass through the root node
  • Time Complexity: O(n), where n is the number of nodes
  • Space Complexity: O(h), where h is the height of the tree (due to recursion stack)
AlgorithmsPwCZomato
Editorial

Login to view the detailed solution and explanation for this problem.

My Submissions
All Solutions
Lang Status Date Code
You do not have any submissions for this problem.
User Lang Status Date Code
No submissions found.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

Solution Hints

  • Use a recursive depth-first search (DFS) approach
  • For each node, calculate the height of its left and right subtrees
  • The diameter passing through a node is the sum of the heights of its left and right subtrees
  • Keep track of the maximum diameter found so far
  • The height of a node is the maximum height of its children plus 1
  • A leaf node has a height of 0

Steps to solve by this approach:

 Step 1: Define a height function that calculates the height of the tree and updates the diameter
 Step 2: For the base case, return 0 if the node is NULL
 Step 3: Recursively calculate the height of the left subtree
 Step 4: Recursively calculate the height of the right subtree
 Step 5: Update the global diameter variable if the path through current node (leftHeight + rightHeight) is longer
 Step 6: Return the height of the current subtree as 1 + max(leftHeight, rightHeight)
 Step 7: In the main function, initialize diameter to 0 and call the height function to calculate the result

Submitted Code :