Grokking the Coding Interview: Patterns for Coding Questions
Ask Author
Back to course home

0% completed

Solution: Problem Challenge 1: Tree Diameter

Problem Statement

Given a binary tree, find the length of its diameter. The diameter of a tree is the number of nodes on the longest path between any two leaf nodes. The diameter of a tree may or may not pass through the root.

Note: You can always assume that there are at least two leaf nodes in the given tree.


  • n == edges.length + 1
  • 1 <= n <= 10<sup>4</sup>
  • 0 <= a<sub>i</sub>, b<sub>i</sub> < n
  • a<sub>i</sub> != b<sub>i</sub>


This problem follows the Binary Tree Path Sum pattern. We can follow the same DFS approach




Like the course? Get enrolled and start learning!