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
给出一棵二叉树,找出其中有相同值的最长路径,这个路径可以不通过root
思路:
观察Example2可以发现不通过root时,结果可用左右路径长相加。
而观察Example1可发现通过root时,结果只能取左右路径中较长的一个。
所以需要一个函数,用左右路径相加更新结果,同时要返回左右路径中较长的一个。
而只有root.val和左右子树root.val相等时,路径长才有1+递归下一个左右子树,直到root==null,路径长返回0
class Solution {
int result = 0;
public int longestUnivaluePath(TreeNode root) {
if(root == null) return 0;
helper(root);
return result;
}
int helper(TreeNode root) {
if(root == null) return 0;
int left = helper(root.left);
int right = helper(root.right);
int leftLen = 0;
int rightLen = 0;
if(root.left != null && root.left.val == root.val) {
leftLen = 1 + left;
}
if(root.right != null && root.right.val == root.val) {
rightLen = 1 + right;
}
result = Math.max(result, leftLen + rightLen);
return Math.max(leftLen, rightLen);
}
}