MEDIUM NC#48 Trees
543. Diameter of Binary Tree
๐ Problem
Given the root of a binary tree, return the length of the diameter of the 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.
๐ง Visual Learning Aid
1 Model the input into the right structure
2 Choose the core technique and invariant
3 Execute step-by-step with a sample
4 Validate complexity and edge cases
JS/TS Refreshers
- โขArray methods (`push`, `pop`, `shift`, `slice`)
- โขObject/Map/Set usage patterns
- โขFunction parameter and return typing
- โขLevel-order traversal
- โขQueue discipline
- โขShortest-step interpretation
Logical Thinking Concepts
- โขDefine invariants before coding
- โขCheck edge cases first (`[]`, single element, duplicates)
- โขEstimate time/space before implementation
- โขApply BFS reasoning pattern
๐ก Approach
- โ Diameter = longest path through any node as the highest point
- โ For each node, find longest path going through it
- โ This is left height + right height
- โ Track max diameter across all nodes
- โ Time: O(n), Space: O(h) where h is tree height
๐งญ Prerequisites
๐ ๏ธ Hints & Pitfalls
Hints
- โขDiameter = longest path through any node as the highest point
- โขFor each node, find longest path going through it
- โขThis is left height + right height
Common Pitfalls
- โขTrack max diameter across all nodes
- โขTime: O(n), Space: O(h) where h is tree height
๐งช Test Cases
Hidden tests on submit: 1
Test Case 1
Not run Input:
depth(node: TreeNode | null); Expected:
Computed from hidden reference Test Case 2
Not run Input:
depth(node.left); Expected:
Computed from hidden reference Test Case 3
Not run Input:
depth(node.right); Expected:
Computed from hidden reference ๐ Code Editor
๐ค Output