← Questions

Diameter of a binary tree

0
MetaAmazonCodingLast asked May 2026

A coding interview question asked in Meta's AI-enabled coding round and at Amazon, last asked May 2026. It tests trees and recursion.

Return the number of edges on the longest path between any two nodes of a binary tree. The path doesn't have to pass through the root. Solve it in one pass over the tree.

Interface

Unless you agree on a different interface with the interviewer, assume:

  • diameter(root: TreeNode | None) -> int — 0 for an empty tree or a single node.
  • In examples the tree is written in level order, with None for a missing child.

Example

diameter([1, 2, 3, 4, 5])                     ->  3   # 4 -> 2 -> 1 -> 3
diameter([1, 2])                              ->  1
diameter([1, 2, None, 3, 4, 5, None, None, 6]) ->  4   # 5 -> 3 -> 2 -> 4 -> 6, not through the root

Constraints

  • 0 <= number of nodes <= 10^4; the tree can be a deep chain.

Clarifying questions

  • Do you count edges or nodes on the path?
  • Can the longest path skip the root?
  • Can the tree be very deep, so recursion might overflow?

What a strong answer covers

  • A post-order DFS that returns each subtree's height; at each node, left_height + right_height is the longest path through it, and the answer is the maximum over all nodes. O(n) time, O(h) stack.
  • Why computing heights separately for every node is O(n^2).
  • An iterative post-order traversal for very deep trees.
  • Tests: an empty tree, a single node, a chain, a path that avoids the root.

Follow-ups

  • Return the nodes on the longest path, not just its length.
  • Edges have weights: return the heaviest path.
  • The diameter of a general tree given as an edge list (two BFS passes).

Where it's asked

  • Meta · AI-enabled coding · Last asked May 202660 min · Several progressive tasks on a starter codebase in CoderPad with an AI assistant panel; usually two rounds · The first task usually without AI, later tasks with it
  • Amazon · Technical phone screen · Last asked Sep 202560 min · Live coding in a shared editor that does not run code, plus Leadership Principles questions · No AI

What it tests

trees · recursion

Write and test your solution herePython in your browser, the question's tests level by level, every submission kept for you.Sign in to start coding