/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: int longestUnivaluePath(TreeNode* root) { int res = 0; helper(root, res); return res; } int helper(TreeNode* root, int &res) { if (root == NULL) return 0; int ret = 0; int left = helper(root->left, res); int right = helper(root->right, res); if (root->left && root->left->val == root->val) { res = max(res, left + 1); ret = left + 1; } if (root->right && root->right->val == root->val) { res = max(res, right + 1); ret = max(ret, right + 1); } if (root->left && root->left->val == root->val && root->right && root->right->val == root->val) res = max(res, left + right + 2); return ret; } };