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.
Input: root = [1,2,3,4,5] Output: 3
4 → 2 → 1 → 3 (or 5 → 2 → 1 → 3) has three edges.
Input: root = [1,2] Output: 1
Only one edge exists.
0 <= number of nodes <= 10^4Trees 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.
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).
I'm here to help with #347 Longest Focus Path. I give hints, never the solution, so you get to solve it yourself. Ask for a hint, select code to ask about it, or press Ask Tuto why on a failing test.
Your first 3 answers need no account. for free to keep asking.