Longest Univalue Path

Given the root of a binary tree, return the length of the longest path where each node in the path has the same value. This path may or may not pass through the root.

The length of the path between two nodes is represented by the number of edges between them.

Example 1
        5
       / \
      4   5
     / \   \
    1   1   5
Inputroot = [5,4,5,1,1,null,5]
Output2
The longest path with the same value consists of nodes with value 5 and has length 2.
Example 2
        1
       / \
      4   5
     / \   \
    4   4   5
Inputroot = [1,4,5,4,4,null,5]
Output2
The longest path with the same value consists of nodes with value 4 and has length 2.

Constraints

  • The number of nodes in the tree is in the range [0, 10^4].
  • -1000 <= Node.val <= 1000
  • The depth of the tree will not exceed 1000.

Asked at 7 companies

</>

Your Solution

(Ctrl/Cmd + Enter)

Switching Language

Loading template...

Loading...

Sign in to save your progress

AI code evaluation

Get a correctness verdict, missed edge cases, and complexity analysis of your solution.

Sign in to evaluate