
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:
- 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:
- 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)
Editorial
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. |
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