问题
Question:
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.
source
A solution to this is:
class Solution
{
public:
int max_len = INT_MIN;
int longestUnivaluePath(TreeNode* root)
{
if(!root)
return 0;
helper(root, root->val);
return max_len;
}
int helper(TreeNode* root, int prev_value)
{
if(!root)
return 0;
int left = helper(root->left, root->val);
int right = helper(root->right, root->val);
max_len = std::max(left + right, max_len); // Why do we do this? I have no idea
if(root->val == prev_value)
return std::max(left, right) + 1;
return 0;
}
};
Why do we do this: max_len = std::max(left + right, max_len);
This part does not make sense to me. If anyone can actually explain it simply I would greatly appreciate the insight.
回答1:
The longest path doesn't have to be strictly descending, right? For example, the length of the longest univalue path in the following tree is 2:
3
/ \
3 3
In their algorithm,left
is the length of the longest descending univalue path down the left branch of node
.right
is the length of the longest descending univalue path down the right branch of node
.
Combined, left + right
is the length of the longest univalue path going through the node node
, which is the new candidate path.
So the line in question actually meansmax_len = std::max(candidate_len, max_len);
which is a canonical running max algorithm: it processes the candidate values sequentially, one by one, and keeps the maximum value seen thus far in max_len
. Eventually, max_len
will end up with the maximum value of all candidates.
来源:https://stackoverflow.com/questions/57714527/leetcode-question-to-finding-the-longest-univalue-path