v9.1.1
Menu

Diameter of Binary Tree

easyPROTrees & BFS/DFSMeta DSA

Given the root of a binary tree (as a level-order array), return the diameter — the length of the longest path between any two nodes.

The length is measured by the number of edges between them.

Example

Input
1,2,3,4,5
Output
3
Reasoning
  • Input: the level-order array 1,2,3,4,5 fills the tree row by row, left to right: 1 is the root, 2 and 3 are its left and right children, and 4 and 5 are both children of 2.
  • Paths between leaves: 4→2→54 \to 2 \to 5 has 22 edges. 4→2→1→34 \to 2 \to 1 \to 3 has 33 edges.
  • Why 33 is the maximum: node 3 sits 11 edge below the root, while 4 and 5 sit 22 edges below it. A path joining the two sides of the root therefore has 2+1=32 + 1 = 3 edges.
  • Output: 3, a count of edges, not nodes: the path 4→2→1→34 \to 2 \to 1 \to 3 visits 44 nodes but uses 33 edges.
  • Notice: the longest path need not touch the root. Drop 3 and hang a child 66 under 4 and a child 77 under 5: then 6→4→2→5→76 \to 4 \to 2 \to 5 \to 7 has 44 edges, while any path touching the root has at most 33. A single-node tree has diameter 00.

Constraints

  • 1 <= number of nodes <= 10^4
  • -100 <= Node.val <= 100

Learn this in

More from Meta DSA

PRO

Editor locked

The code editor is locked for Pro problems. It is only available for free problems. Please upgrade to gain access to the code editor for all problems.

solution.py

Test results

Sign in to run your code against the test cases.