Reference URL: https://leetcode.com/problems/longest-univalue-path/discuss/108136/JavaC%2B%2B-Clean-Code
Problem-solving ideas:
(1) Thinking of a binary tree, the most commonly used is recursion. The following mainly explains the two parts of the code
(2) return max (resl, resr); it represents a path, so there can be no branches.
(3) So for a node, we choose the longest path in the left and right subtree
(4) But if this branch is at the root node, then it is acceptable, lup = max (lup, resl + resr) is to do this
(5) Existence is reasonable, if there is a certain node, take it as a turning point, the length is greater than the current lup, then update the value of lup
(6) But it does not rule out that there will be a larger value in the follow-up, here lup only means that there is a certain path, we do not record
(7) This technique is very similar to the previous Longest Increasing Subsequence (C ++ longest rising subsequence), the URL is as follows:
(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);
}
};