> For the complete documentation index, see [llms.txt](https://soumyajit4419.gitbook.io/ds-algo/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://soumyajit4419.gitbook.io/ds-algo/binary-tree/problems-related-to-binary-trees/24.-longest-univalue-path.md).

# 24. 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:**![](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
```

## Solution: (DFS / Postorder Traversal)

**Approach:** \
**Similar to diameter**

```cpp
class Solution
{
public:
    int ans = 0;
    int findPath(TreeNode *root)
    {

        if (root == NULL)
        {
            return 0;
        }

        int x = findPath(root->left);
        int y = findPath(root->right);

        int left = 0;
        int right = 0;
        if (root->left && root->val == root->left->val)
        {
            left += x + 1;
        }

        if (root->right && root->val == root->right->val)
        {
            right += y + 1;
        }

        ans = max(ans, left + right);

        return max(left, right);
    }

    int longestUnivaluePath(TreeNode *root)
    {
        if (root == NULL)
        {
            return 0;
        }
        findPath(root);
        return ans;
    }
};
```
