Longest Univalue Path

Given the `root` of a binary tree, return the length of the longest path in which every node has the same value. The path may or may not pass through the root. The length of a path is the number of **edges** between its two end nodes.

30:00

Longest Univalue Path
medium
Free written solution
Topics
Companies

Given the root of a binary tree, return the length of the longest path in which every node has the same value. The path may or may not pass through the root.

The length of a path is the number of edges between its two end nodes.

Example 1:
Input: {"root":[5,4,5,1,1,null,5]}
Output: 2
Constraints:
  • The number of nodes in the tree is in the range [0,104][0, 10^4].

  • −1000≤Node.val≤1000-1000 \leq \text{Node.val} \leq 1000

  • The depth of the tree will not exceed 10001000.

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"root":[5,4,5,1,1,null,5]}

best starts at 0. Each call returns the longest same-value arm hanging down from its node, counted in edges.

best (edges)

0

545115
solid: equal values
left arm
right arm
best path
↑k: arm returned
Variables
VariableValue
best0
DepthFunction Call
Stack empty
0/9