Skip to the code
cf.
+10 XP

#347 Longest Focus Path

easy

Keyboard focus moves along the edges of a layout tree, one step per edge. QA wants to know the longest trip focus could ever make between two nodes without visiting a node twice.

Write longestPath(root) that returns the number of edges on the longest path between any two nodes. The path doesn't have to pass through the root. A tree with zero or one node returns 0.

Example 1

Input: root = [1,2,3,4,5]
Output: 3

4 → 2 → 1 → 3 (or 5 → 2 → 1 → 3) has three edges.

Example 2

Input: root = [1,2]
Output: 1

Only one edge exists.

Constraints

  • 0 <= number of nodes <= 10^4

Trees are written level by level, like [1, 2, 3, null, 4], where null is a missing child. Your function works with TreeNode objects, each with val, left, and right.

Saved in this browser

Run tries your code on the examples. Submit runs every test, including hidden edge cases, and solves the problem when they all pass.

Ctrl + Enter runs, Ctrl + Shift + Enter submits (⌘ on a Mac).