Leetcode question to finding the longest univalue path [closed]

不打扰是莪最后的温柔 提交于 2020-04-30 09:12:21

问题


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 means
max_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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!