← Google Interview Insights

Google·Software Engineer·Technical Phone Screen·Intermediate

IntermediatePrefer not to say
Apr 2026

Summary

Google SWE coding round, just one question on binary tree diameter. Pretty standard but I second-guessed myself more than I should have.

Questions Asked (1)

Q1

Given the root of a binary tree, find the length of the tree's diameter.

Algorithms & Data Structures
Author's notes

I knew the trick was that the diameter doesn't have to pass through the root, which I almost forgot until I started drawing it out.

Create a free account to read the full note

AI HintsAI Generated

Suggested Approach

Clarify that the diameter is the number of edges on the longest path between any two nodes, which may or may not pass through the root. Then propose a post-order DFS that computes each node's height while tracking the maximum left-height + right-height seen so far, yielding O(n) time and O(h) space.

Pro tip: Mention that the diameter path doesn't have to pass through the root—many candidates assume it does and fail edge cases. Also note that if the problem defines diameter as node count instead of edge count, the answer differs by one, so confirm the definition upfront.

1. Clarify the definition and constraints

Confirm whether diameter is measured in edges or nodes, and ask about tree size, balance, and whether the tree can be empty or a single node. This shows you think about edge cases before coding.

2. Explain the brute-force baseline

Briefly describe the naive O(n^2) approach: for each node, compute left and right heights and take the max. This demonstrates you can reason from first principles before optimizing.

3. Derive the O(n) post-order DFS

Explain that a single DFS can return each subtree's height to its parent while updating a global maximum with leftHeight + rightHeight at each node. Emphasize that the diameter through a node is the sum of its children's heights.

4. Walk through a small example

Trace the algorithm on a small tree (e.g., a root with two deep subtrees) to show how the global maximum is updated and why the path need not pass through the root.

5. State complexity and edge cases

Conclude with O(n) time and O(h) space (O(n) worst case for skewed trees), and mention handling of empty tree, single node, and skewed trees.

Key Points to Mention

  • Diameter is the longest path between any two nodes and may not pass through the root
  • Post-order DFS computes subtree heights bottom-up in a single pass
  • At each node, candidate diameter = leftHeight + rightHeight
  • Use a global/instance variable or return a tuple to track the maximum
  • Time complexity O(n), space complexity O(h) due to recursion stack
  • Edge cases: empty tree (diameter 0), single node (diameter 0 in edges), skewed tree (height = n-1)

AI-generated suggestions, not part of the candidate's original notes. May be inaccurate — verify before relying on them.