Longest Univalue Path

MediumTreestree dp

Solve this the way you would in the interview: out loud, on a timer, with an AI interviewer asking follow-ups while you code. You get a scored report at the end.

Practice this as a mock interviewFree to start, no account needed

Problem

Given the root of a binary tree, return the length of the longest path in which every node has the same value. A path is any sequence of nodes connected by parent-child edges, with no node repeated. It does not have to pass through the root, and it may go up through a node and back down the other side. The length of a path is its number of **edges**. An empty tree or a single node has answer 0.

Examples

Input: root = [5,4,5,1,1,null,5]
Output: 2
The path 5 - 5 - 5 down the right side has two edges.
Input: root = [1,4,5,4,4,null,5]
Output: 2
The path 4 - 4 - 4 bends through the left child.

Constraints

  • 0 <= number of nodes <= 10^4
  • -1000 <= Node.val <= 1000
  • The depth of the tree is at most 1000

What the interviewer grades

A correct solution is one of five scores. The report also grades problem understanding (did you clarify inputs and edge cases before coding), problem solving, communication while you work, code quality, and testing. See a sample report, or read up on the pattern in the lessons.

More tree dp problems