Skip to content

Commit 944de73

Browse files
committed
fd
1 parent d68d090 commit 944de73

File tree

1 file changed

+27
-0
lines changed

1 file changed

+27
-0
lines changed
Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
public class LongestUnivaluePath {
2+
3+
public int longestUnivaluePath(TreeNode root) {
4+
int[] res = new int[1];
5+
dfs(root, res);
6+
return res[0];
7+
}
8+
9+
private int dfs(TreeNode node, int[] res) {
10+
if (node == null) {
11+
return 0;
12+
}
13+
int left = dfs(node.left, res);
14+
int right = dfs(node.right, res);
15+
16+
int lval = 0, rval = 0;
17+
18+
if (node.left != null && node.left.val == node.val) {
19+
lval = left + 1;
20+
}
21+
if (node.right != null && node.right.val == node.val) {
22+
rval = right + 1;
23+
}
24+
res[0] = Math.max(res[0], lval + rval);
25+
return Math.max(lval, rval);
26+
}
27+
}

0 commit comments

Comments
 (0)