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.
The length of path between two nodes is represented by the number of edges between them.
Example 1:
Input:
5 / \ 4 5 / \ \ 1 1 5
Output: 2
Example 2:
Input:
1 / \ 4 5 / \ \ 4 4 5
Output: 2
Note: The given binary tree has not more than 10000 nodes. The height of the tree is not more than 1000.
计算数值相同节点的最长路径
与上题不同点是,本题计算的是路径,有相同的节点,连成一条路
代码如下:
/**
* 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 {
public:
int dfs(TreeNode* root, int& len)
{
if(root == NULL)
return 0;
int l = dfs(root->left,len);
int r = dfs(root->right,len);
int sum = 0, lm = 0, rm = 0;
if(root->left && root->left->val == root->val)
lm = l + 1;
if(root->right && root->right->val == root->val)
rm = r + 1;
sum = lm + rm;
len = max(sum,len);
return max(lm,rm);
}
int longestUnivaluePath(TreeNode* root) {
int len = 0;
if(root == NULL) return 0;
dfs(root,len);
return len;
}
};