Likou question: 687. The longest path with the same value
Given a binary tree, find the longest path, each node in this path has the same value. This path may or may not pass through the root node.
Note: The length of the path between two nodes is represented by the number of edges between them.
Example 1:
enter:
5
/ \
4 5
/ \ \
1 1 5
Output:
2
Example 2:
enter:
1
/ \
4 5
/ \ \
4 4 5
Output:
2
Source: LeetCode
Link: https://leetcode-cn.com/problems/longest-univalue-path
Copyright is owned by LeetCode . For commercial reprints, please contact the official authorization. For non-commercial reprints, please indicate the source.
Refer to the comment area @Jingfu's solution: java official solution thinking analysis: https://github.com/echofoo/ARTS/blob/master/A-20190925-longest path with the same value.md
/**
* 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 ret;
int get_maxlen(TreeNode* root){
if (root == NULL){
return 0;//叶子节点,返回0
}
int leftlen=get_maxlen(root->left);
int rightlen=get_maxlen(root->right);
int left=0,right=0; //当左右子树不相等的时候,不会进入if条件,将返回0
if (root->right && root->val==root->right->val){
right = rightlen+1;
}
if (root->left && root->val==root->left->val){
left=leftlen+1;
}
ret = ret>left+right?ret:left+right;//如果递归回到根节点,那么这个就是我们最终需要的值
return left>right?left:right;//返回左右子树中长度较长的一个分支
}
int longestUnivaluePath(TreeNode* root) {
ret = 0;
get_maxlen(root);
return ret;
}
};