# 0687. Longest Univalue Path

<https://leetcode.com/problems/longest-univalue-path>

## Description

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:**

![](https://assets.leetcode.com/uploads/2020/10/13/ex1.jpg)

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

**Example 2:**

![](https://assets.leetcode.com/uploads/2020/10/13/ex2.jpg)

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

**Constraints:**

* The number of nodes in the tree is in the range `[0, 104]`.
* `-1000 <= Node.val <= 1000`
* The depth of the tree will not exceed `1000`.

## ac

```java
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    int max;
    public int longestUnivaluePath(TreeNode root) {
        max = 0;
        unilateralLen(root);
        return max;
    }

    private int unilateralLen(TreeNode root) {
        // exit
        if (root == null) return 0;

        int left = unilateralLen(root.left);
        int right = unilateralLen(root.right);

        int l = root.left != null && root.val == root.left.val ? left + 1 : 0;
        int r = root.right != null && root.val == root.right.val ? right + 1 : 0;

        max = Math.max(max, l + r); // update max

        return Math.max(l, r);
    }
}
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://jaywin.gitbook.io/leetcode/solutions/0687-longest-univalue-path.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
