//给定一个二叉树,找到最长的路径,这个路径中的每个节点具有相同值。 这条路径可以经过也可以不经过根节点。 
//
// 注意:两个节点之间的路径长度由它们之间的边数表示。 
//
// 示例 1: 
//
// 输入: 
//
// 
//              5
//             / \
//            4   5
//           / \   \
//          1   1   5
// 
//
// 输出: 
//
// 
//2
// 
//
// 示例 2: 
//
// 输入: 
//
// 
//              1
//             / \
//            4   5
//           / \   \
//          4   4   5
// 
//
// 输出: 
//
// 
//2
// 
//
// 注意: 给定的二叉树不超过10000个结点。 树的高度不超过1000。 
// Related Topics 树 递归 
// 👍 424 👎 0

/*
* 687 最长同值路径
* 2021-02-21 19:54:43
* @author oxygenbytes
*/ 
#include "leetcode.h" 
//leetcode submit region begin(Prohibit modification and deletion)
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    int ans = 0;
    int longestUnivaluePath(TreeNode* root) {
        if(!root) return 0;
        dfs(root);
        return ans;
    }
    int dfs(TreeNode* root){ // return root and its any node single path
        if(!root) return 0;
        int l = dfs(root->left);
        int r = dfs(root->right);
        int pl = 0;
        int pr = 0;
        if(root->left && root->val == root->left->val) pl = l + 1;
        if(root->right && root->val == root->right->val) pr = r + 1;
        ans = max(ans, pl + pr);
        return max(pl, pr);
    }
};
//leetcode submit region end(Prohibit modification and deletion)