687. The value of the path with the longest
Given a binary tree, to find the longest paths, each node in this path have 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 therebetween.
Example 1:
Input:
5
/ \
4 5
/ \ \
1 1 5
Output:
2
Example 2:
Input:
1
/ \
4 5
/ \ \
4 4 5
Output:
2
Note: the given binary tree not more than 10,000 nodes. Height of the tree does not exceed 1000.
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
private int maxL = 0;
public int longestUnivaluePath(TreeNode root) {
if(root == null) return 0;
getMaxL(root, root.val);
return maxL;
}
private int getMaxL(TreeNode r, int val) {
if(r == null) return 0;
int left = getMaxL(r.left, r.val);
int right = getMaxL(r.right, r.val);
maxL = Math.max(maxL, left+right); // 路径长度为节点数减1所以此处不加1
if(r.val == val) // 和父节点值相同才返回以当前节点所能构成的最长通知路径长度, 否则返回0
return Math.max(left, right) + 1;
return 0;
}
}