* Definition for a binary tree node.
* public class TreeNode {
* TreeNode(int x) { val = x; }
public int longestUnivaluePath(TreeNode root) {
getLongestUnivaluePath(root, root.val, res);
public int getLongestUnivaluePath(TreeNode node, int val, int[] res) {
int leftPath = getLongestUnivaluePath(node.left, node.val, res);
int rightPath = getLongestUnivaluePath(node.right, node.val, res);
res[0] = Math.max(res[0], leftPath + rightPath);
return val == node.val ? Math.max(leftPath, rightPath) + 1 : 0;