Given the root of a binary tree, return 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.
The length of the path between two nodes is represented by the number of edges between them.
Example 1:
Input: root = [5,4,5,1,1,5]
Output: 2
Example 2:
Input: root = [1,4,5,4,4,5]
Output: 2
Constraints:
The number of nodes in the tree is in the range [0, 104].
-1000 <= Node.val <= 1000
The depth of the tree will not exceed 1000.
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/longest-univalue-path
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
递归调用,递归函数返回的不是子节点的最长路径值,而是子节点能连上当前根节点的最大长度,即要么是他的左子树要么是他的右子树,取最大的那个,这样子才能街上根节点。
class Solution {
int ans = 0;
public int longestUnivaluePath(TreeNode root) {
if (root == null) {
return 0;
}
check(root);
return ans;
}
private int check(TreeNode root) {
if (root == null) {
return 0;
}
int left = check(root.left);
int right = check(root.right);
// 如果当前节点和左子节点一样,那么就可以把左边的数量和当前根节点的1个拼上来,left++
if (root.left != null && root.val == root.left.val) {
left++;
} else {
left = 0;
}
if (root.right != null && root.val == root.right.val) {
right++;
} else {
right = 0;
}
ans = Math.max(ans, left + right);
return Math.max(left, right);
}
}