Diameter of Binary Tree
LeetCode 543 · Easy · solution, intuition & step-by-step walkthrough
diameter = max over nodes of (left height + right height).
This is how I solved Diameter of Binary Tree (LeetCode 543), an easy problem from the Tree DP pattern. Below: the intuition, the approach step by step, my accepted Python code, animated test cases and a line-by-line debugger.
Intuition
The longest path bends at some node, going down its left side and its right side. At each node that length is left height + right height. Compute heights bottom-up and keep the best sum seen.
Approach
- 1
dfs returns the height of a subtree.
- 2
At each node, update the best with lh + rh.
- 3
Return 1 + max(lh, rh).
How I solved it
Height DFS with global bestPythonO(n) time · O(h) space
class Solution:
def diameterOfBinaryTree(self, root):
self.maxDepth = float("-inf")
def dfs(node):
if node is None:
return 0
lh = dfs(node.left)
rh = dfs(node.right)
self.maxDepth = max(self.maxDepth, lh + rh)
return 1 + max(lh, rh)
dfs(root)
return self.maxDepthDiameter of Binary Tree — FAQ
What is the intuition behind Diameter of Binary Tree?
The longest path bends at some node, going down its left side and its right side. At each node that length is left height + right height. Compute heights bottom-up and keep the best sum seen.
How do you solve Diameter of Binary Tree (LeetCode 543)?
1. dfs returns the height of a subtree. 2. At each node, update the best with lh + rh. 3. Return 1 + max(lh, rh).
What is the time and space complexity of Diameter of Binary Tree?
Time: O(n). Space: O(h). (Accepted approach: Height DFS with global best.)
What are common mistakes in Diameter of Binary Tree?
The path doesn't have to pass through the root.