-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlc-687.java
More file actions
26 lines (26 loc) · 751 Bytes
/
lc-687.java
File metadata and controls
26 lines (26 loc) · 751 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
private int max = 0;
public int longestUnivaluePath(TreeNode root) {
if(root != null) {
int len = calculate(root.left, root.val) + calculate(root.right, root.val);
if(len>max)max = len;
longestUnivaluePath(root.left);
longestUnivaluePath(root.right);
}
return max;
}
private int calculate(TreeNode t, int pval) {
if(t==null) return 0;
if(t.val == pval) return Math.max(calculate(t.left, pval), calculate(t.right, pval)) + 1;
else return 0;
}
}