Given a binary tree, find the length of the longestpath where each node in the path has the same value. This path may or may notpass through the root.
Note: Thelength of path between two nodes is represented by the number of edges betweenthem.
Example 1:
Input:
5
/ \
4 5
/ \ \
1 1 5
Output:
2
Example 2:
Input:
1
/ \
4 5
/ \ \
4 4 5
Output:
2
Note: Thegiven binary tree has not more than 10000 nodes. The height of the tree is notmore than 1000.
这一题虽然是一道easy题,但是比一般的easy题要难,
这一题使用DFS递归解决,每一个递归点的功能是,在每一个递归点进入的时候,需要传给它从父亲节点到儿子节点一直到当前节点的最大长度,每一个递归点在进入任何一个子树的时候,需要传入父亲节点到儿子节点一直到当前节点的最大长度,在任何一个节点运算完成,返回父节点的时候,需要计算左右节点的返回值之和是否能够更新longpath,然后将左右节点得到的父亲节点到儿子节点一直到当前节点的最大长度中的较长的一个返回上一级
class Solution {
public:
int P(int &theLongestPath, TreeNode * root,int theLength)
{
if (root == NULL) return 0;
int leftCount = 0;
int rightCount = 0;
if (root->left!=NULL&& root->left->val == root->val)
{
theLongestPath = max(theLength + 1, theLongestPath);
leftCount=P(theLongestPath, root->left, theLength + 1)+1;
}
else
{
P(theLongestPath, root->left, 0);
}
if (root->right != NULL&&root->right->val == root->val)
{
theLongestPath = max(theLength + 1, theLongestPath);
rightCount=P(theLongestPath, root->right, theLength + 1)+1;
}
else
{
P(theLongestPath, root->right, 0);
}
theLongestPath = max(leftCount+rightCount, theLongestPath);
return max(leftCount, rightCount);
}
int longestUnivaluePath(TreeNode* root) {
int theLongestPath = 0;
P(theLongestPath, root, 0);
return theLongestPath;
}
};