Ctrl K

Longest Path in a Tree

Easy
You are given the root of a binary tree. A path is a chain of nodes where neighbours are joined by an edge and no node appears twice. Its length is the number of edges it contains. Return the length of the longest path between any two nodes of the tree. The path does not have to pass through the root.
Example 1
root=tree_node([6, 3, None, 8, 2, 7, None, None, 5]) → 4

The longest path is 7 → 8 → 3 → 2 → 5: it has 4 edges and does not go through the root 6 at all.

Example 2
root=tree_node([1, -4, 9]) → 2

The path -4 → 1 → 9 has two edges.

Example 3
root=tree_node([42]) → 0

A single node gives a path with no edges, length 0.

Constraints
  • 1 ≤ number of nodes ≤ 10⁵
  • -100 ≤ Node.val ≤ 100
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsLeft, Node, Right EasyIdentical Trees EasyMirror-Image Tree EasyTree Height EasyEvenly Grown Tree Easy
loading Python…
Input
root=tree_node([6, 3, None, 8, 2, 7, None, None, 5])
Expected
4

Run checks the first 3 tests in your browser. Submit checks all 96 tests on the server, hidden ones included.