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

๐Ÿ› ๏ธ 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

๐Ÿ“š Reference Solution

โ–ผ
โŒ˜K Search โŒ˜โ†ฉ Run โŒ˜S Submit