https://leetcode.com/problems/longest-univalue-path/description/
哟意思和有点难度的地方 在一次dfs做两个事情
/**
* 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 dfs( TreeNode* root, int &cur_ans) {
if (!root) return 0;
int lcnt = 0, rcnt = 0;
if (root->left) {
if (root->left->val == root->val) {
lcnt = dfs(root->left, cur_ans);
} else {
dfs(root->left, cur_ans);
}
}
if (root->right) {
if (root->right->val == root->val) {
rcnt = dfs(root->right, cur_ans);
} else {
dfs(root->right, cur_ans);
}
}
cur_ans = max(cur_ans, lcnt + rcnt + 1);
int ret = max(lcnt, rcnt) + 1;
cur_ans = max(cur_ans, ret);
return ret;
}
int longestUnivaluePath(TreeNode* root) {
if (!root) return 0;
int child_ans = 0;
int ret = dfs(root, child_ans);
return max(ret, child_ans) - 1;
}
};