leetcode 687.Longest Univalue Path

Posted newnoobbird

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了leetcode 687.Longest Univalue Path相关的知识,希望对你有一定的参考价值。

寻找最长的路径,那么会在左边或者右边或者是从左到跟然后再到右方的路径的。

/**
 * 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=max(longestUnivaluePath(root->left), longestUnivaluePath(root->right));
        return max(res, helper(root->left, root->val)+helper(root->right, root->val));
    }
    int helper(TreeNode* root, int parent){
        if(!root || root->val!=parent) return 0;
        return 1+max(helper(root->left, parent), helper(root->right, parent));
    }
};

 

以上是关于leetcode 687.Longest Univalue Path的主要内容,如果未能解决你的问题,请参考以下文章

[LeetCode] 687. Longest Univalue Path 最长唯一值路径

leetcode 687.Longest Univalue Path

[LeetCode] 687. Longest Univalue Path

687. Longest Univalue Path

687. Longest Univalue Path 687.最长单值路径

687. Longest Univalue Path 687.最长单值路径