[LeetCode] Longest Univalue Path

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.

Note: The length of path between two nodes is represented by the number of edges between them.

Example 1:

Input:

              5
             / 
            4   5
           /    
          1   1   5

Output:

2

Example 2:

Input:

              1
             / 
            4   5
           /    
          4   4   5

Output:

2

Note: The given binary tree has not more than 10000 nodes. The height of the tree is not more than 1000.

寻找由相同值组成的最长路径(路径可以不经过根节点),对于关于树的路径问题应该是递归的思想来解题。

首先应该找出该问题的子问题,也就是说树的最小部分问题。也就是如果一个父节点与其子节点值相同,则将其计数+1。一般情况下,一个父节点存在两个子节点,这时需要判断它的左子树的计数大还是右子树计算大。返回较大的那个值,同时还需要更新每个节点的最大路径。

/**
 * 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) {
        int lup = 0;
        if (root != nullptr)
            dfs(root, lup);
        return lup;
    }
    int dfs(TreeNode* node, int& lup) {
        int l = node->left ? dfs(node->left, lup) : 0;
        int r = node->right ? dfs(node->right, lup) : 0;
        int resl = node->left && node->left->val == node->val ? l + 1 : 0;
        int resr = node->right && node->right->val == node->val ? r + 1 : 0;
        lup = max(lup, resl + resr);
        return max(resl, resr);
    }
};
// 99 ms
原文地址:https://www.cnblogs.com/immjc/p/7778291.html