【同124】LeetCode 687. Longest Univalue Path

LeetCode 687. Longest Univalue Path

Solution1:
参考链接:http://zxi.mytechroad.com/blog/tree/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 ans = 0;
        my_DFS(root, ans);
        return ans;
    }

    int my_DFS(TreeNode* root, int& ans) {
        int sum = 0;
        if (!root) return 0;
        int l = my_DFS(root->left, ans);
        int r = my_DFS(root->right, ans);
        int pl = 0, pr = 0;
        if (root->left && root->val == root->left->val) 
            pl = l + 1;
        if (root->right && root->val == root->right->val) 
            pr = r + 1;
        ans = max(ans, pl + pr);
        return max(pl, pr);
    }
};

猜你喜欢

转载自blog.csdn.net/allenlzcoder/article/details/80871668