0687.cpp (406B)
1 class Solution { 2 int res = 0; 3 4 int rec(const TreeNode *root, int parent) { 5 if (!root) return 0; 6 7 const auto l = rec(root->left, root->val), r = rec(root->right, root->val); 8 9 res = max(res, l + r); 10 return root->val == parent ? max(l, r) + 1 : 0; 11 } 12 13 public: 14 int longestUnivaluePath(const TreeNode *root) { 15 rec(root, -1); 16 return res; 17 } 18 };