-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathLongestUnivaluePath.java
38 lines (31 loc) · 1.02 KB
/
LongestUnivaluePath.java
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
27
28
29
30
31
32
33
34
35
36
37
38
package com.smlnskgmail.jaman.leetcodejava.medium;
import com.smlnskgmail.jaman.leetcodejava.support.TreeNode;
// https://leetcode.com/problems/longest-univalue-path/
public class LongestUnivaluePath {
private final TreeNode input;
private int result;
public LongestUnivaluePath(TreeNode input) {
this.input = input;
}
public int solution() {
findPath(input);
return result;
}
private int findPath(TreeNode node) {
if (node != null) {
int arrowLeft = 0;
int left = findPath(node.left);
if (node.left != null && node.left.val == node.val) {
arrowLeft += left + 1;
}
int arrowRight = 0;
int right = findPath(node.right);
if (node.right != null && node.right.val == node.val) {
arrowRight += right + 1;
}
result = Math.max(result, arrowLeft + arrowRight);
return Math.max(arrowLeft, arrowRight);
}
return 0;
}
}