Posted on

Description

Submission

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

    int longestUnivaluePathUtil(TreeNode* root, int val) {
        if(!root) return 0;
        if(root->val != val) return 0;
        return longestUnivaluePathMax(root->right, val) + longestUnivaluePathMax(root->left, val);
    }
public:
    int longestUnivaluePath(TreeNode* root) {
        if(!root) return 0;
        int ret = max(longestUnivaluePathUtil(root, root->val), longestUnivaluePath(root->left));
        return max(ret, longestUnivaluePath(root->right));
    }
};

Leave a Reply

Your email address will not be published. Required fields are marked *