#543
Diameter of Binary Tree
EasyTreeDepth-First SearchBinary TreeDepth-First SearchTree Traversal
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(h) |
💡
Intuition
Time O(n)Space O(h)
The optimal solution uses a single depth-first search (DFS) to calculate the diameter in one pass. By keeping track of the maximum diameter during the traversal, we avoid redundant calculations and achieve better efficiency.
⚙️
Algorithm
3 steps- 1Step 1: Initialize a variable to keep track of the maximum diameter.
- 2Step 2: Perform a DFS on the tree, calculating the height of each subtree.
- 3Step 3: During the DFS, update the maximum diameter whenever a node's left and right heights are summed.
solution.py20 lines
1# Full working Python code
2class TreeNode:
3 def __init__(self, val=0, left=None, right=None):
4 self.val = val
5 self.left = left
6 self.right = right
7
8class Solution:
9 def diameterOfBinaryTree(self, root: TreeNode) -> int:
10 def dfs(node):
11 if not node:
12 return 0
13 left = dfs(node.left)
14 right = dfs(node.right)
15 self.max_diameter = max(self.max_diameter, left + right)
16 return max(left, right) + 1
17
18 self.max_diameter = 0
19 dfs(root)
20 return self.max_diameterℹ
Complexity note: The time complexity is O(n) because we visit each node exactly once. The space complexity is O(h) due to the recursion stack, where h is the height of the tree.
- 1The diameter can be calculated without explicitly finding all pairs of nodes, making the optimal solution much more efficient.
- 2Understanding how to traverse a tree using DFS is crucial for solving many tree-related problems.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.