Diameter of Binary Tree
Return the diameter (longest path in edges) of a binary tree. Example: [1,2,3,4,5] => 3
Diameter of Binary Tree teaches the post-order trick that powers half of all tree problems: each node returns its height while a side variable tracks the best answer seen. The path that matters rarely runs through the root, so a top-down count fails. Once the height-plus-side-effect pattern clicks, max-path-sum feels familiar.
Examples
You write
diameter_of_binary_tree(root: Optional[TreeNode])
Example 1
- Input
- [1,2,3,4,5]
- returns
- 3
Example 2
- Input
- [1,2]
- returns
- 1
The pattern behind it
Trees
I reach for it when
- Each node has children, and the answer depends on the subtrees.
- The statement says depth, height, ancestor or path.
Say this before you type. Say what a call returns for an empty tree, and what it returns for a node.
All 22 Trees problemsBFS & DFS
I reach for it when
- You walk a grid, a graph or a tree and visit each cell once.
- The word shortest appears and every step costs the same.
Say this before you type. Say why breadth or depth fits, and exactly when a cell counts as visited.
All 52 BFS & DFS problems
Meet Coco
Coco is an AI study partner, not a person. She listens while you explain your code, asks what a line does and never hands you the fix. Sign in free to type with Coco, up to a daily limit. The editor and Run stay open without an account. Anyone can open the editor and run their code.
Prep guides that list this problem
Our company tags come from public interview write-ups. None of these is a confirmed question.