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));
    }
};

猜你喜欢

转载自www.cnblogs.com/newnoobbird/p/9631766.html