[leetcode]687. Longest Univalue Path
Analysis
ummmm~—— [ummmm~]
Given a binary tree, find the length of the longest path where each node in the path has the same value. This path may or may not pass through the root.
递归解决,这篇博客讲得比较清楚:http://www.cnblogs.com/grandyang/p/7636259.html
Implement
/**
* 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) {
if(!root)
return 0;
int res = 0;
DFS(root, res);
return res;
}
int DFS(TreeNode* root, int &res){
if(!root)
return 0;
int l = DFS(root->left, res);
int r = DFS(root->right, res);
if(root->left && root->val == root->left->val)
l = l + 1;
else
l = 0;
if(root->right && root->val == root->right->val)
r = r + 1;
else
r = 0;
res = max(res, l + r);
return max(l, r);
}
};