题目链接:https://leetcode.cn/problems/longest-univalue-path/
C++ 代码如下:
/**
* 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 {
private:
int res;
public:
int longestUnivaluePath(TreeNode* root) {
res = 0;
longest(root);
return res;
}
int longest(TreeNode* root) {
if (root == nullptr) return 0;
int left = longest(root->left);
int right = longest(root->right);
if (root->left != nullptr && root->left->val == root->val) {
left++;
} else {
left = 0;
}
if (root->right != nullptr && root->right->val == root->val) {
right++;
} else {
right = 0;
}
res = max(res, left + right);
return max(left, right);
}
};