[LeetCode] Problem 687 - Longest Univalue Path

Given a binary tree, find 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 path between two nodes is represented by the number of edges between them.

Example

No.1

Input:

1
2
3
4
5
    5
/ \
4 5
/ \ \
1 1 5

Output: 2

No.2

Input:

1
2
3
4
5
    1
/ \
4 5
/ \ \
4 4 5

Output: 2

Note

The given binary tree has not more than 10000 nodes. The height of the tree is not more than 1000.

Code

1
2
3
4
5
6
public class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) { val = x; }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
private int max = 0;

public int longestUnivaluePath(TreeNode root) {
pathHelper(root, -1);
return max;
}

private int pathHelper(TreeNode root, int parent) {
if (root == null)
return 0;

int left = pathHelper(root.left, root.val);
int right = pathHelper(root.right, root.val);

max = Math.max(max, left + right);

return root.val == parent ? Math.max(left, right) + 1 : 0;
}