---
# System prepended metadata

title: 0687. Longest Univalue Path
tags: [Leetcode, Tree, Medium]

---

# 0687. Longest Univalue Path
###### tags: `Leetcode` `Medium` `Tree`
Link: https://leetcode.com/problems/longest-univalue-path/
## 思路
dfs找的是包含root的最长uniquevalue path的长度
## Code
```java=
class Solution {
    int len = 0;
    public int longestUnivaluePath(TreeNode root) {
        dfs(root);
        return len;
    }
    private int dfs(TreeNode root){
        if(root == null) return 0;
        int curr = 0;
        int left = dfs(root.left);
        int right = dfs(root.right);
        
        int arrowLeft = 0, arrowRight = 0;
        if(root.left!=null && root.left.val==root.val) arrowLeft = left+1;
        if(root.right!=null && root.right.val==root.val) arrowRight = right+1;
        
        len = Math.max(len, arrowLeft+arrowRight);
        return Math.max(arrowLeft, arrowRight);
    }
}
```