Longest Univalue Path(C++最长同值路径)

参考网址:https://leetcode.com/problems/longest-univalue-path/discuss/108136/JavaC%2B%2B-Clean-Code

解题思路:

(1)想到二叉树,可能最常用的就是递归,以下主要解释代码的两个部分

(2)return max(resl, resr);表示的是一条路径,因此不能有分支。

(3)所以我们对于一个结点而言,选择的最长路径是在左右子树中选择的

(4)但是如果这分支是在根结点,那么就可以接受,lup = max(lup, resl + resr)就是做这件事的

(5)存在即合理,如果存在某个节点,以它为转折点,长度大于目前的lup,那么更新lup的值

(6)但是不排除后续会有更大的值,这里lup只是表示存在某条路径,我们并不记录

(7)这一技巧和前面的Longest Increasing Subsequence(C++最长上升子序列)很像,网址如下:

(8)https://blog.csdn.net/coolsunxu/article/details/105403508

class Solution {
public:
    int longestUnivaluePath(TreeNode* root) {
        int lup = 0;
        if (root) dfs(root, lup);
        return lup;
    }

private:
    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);
    }
};
发布了303 篇原创文章 · 获赞 277 · 访问量 42万+

猜你喜欢

转载自blog.csdn.net/coolsunxu/article/details/105530501