Skip to content

Commit 07f69ad

Browse files
authored
Create 687. Longest Univalue Path
1 parent f3c7283 commit 07f69ad

File tree

1 file changed

+71
-0
lines changed

1 file changed

+71
-0
lines changed

687. Longest Univalue Path

Lines changed: 71 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,71 @@
1+
/*
2+
// Given a binary tree, find the length of the longest path where each node in the path has the same value.
3+
// This path may or may not pass through the root.
4+
5+
// Note: The length of path between two nodes is represented by the number of edges between them.
6+
7+
Example 1:
8+
Input:
9+
10+
5
11+
/ \
12+
4 5
13+
/ \ \
14+
1 1 5
15+
Output:
16+
2
17+
18+
Example 2:
19+
Input:
20+
21+
1
22+
/ \
23+
4 5
24+
/ \ \
25+
4 4 5
26+
Output:
27+
2
28+
*/
29+
30+
/**
31+
* Definition for a binary tree node.
32+
* public class TreeNode {
33+
* int val;
34+
* TreeNode left;
35+
* TreeNode right;
36+
* TreeNode(int x) { val = x; }
37+
* }
38+
*/
39+
40+
class Solution {
41+
int result;
42+
43+
public int longestUnivaluePath(TreeNode root) {
44+
result = 0;
45+
arrowLength(root);
46+
return result;
47+
}
48+
49+
public int arrowLength(TreeNode node) {
50+
if (node == null) {
51+
return 0;
52+
}
53+
54+
int left = arrowLength(node.left);
55+
int right = arrowLength(node.right);
56+
57+
int arrowLeft = 0, arrowRight = 0;
58+
59+
if (node.left != null && node.left.val == node.val) {
60+
arrowLeft += left + 1;
61+
}
62+
63+
if (node.right != null && node.right.val == node.val) {
64+
arrowRight += right + 1;
65+
}
66+
67+
result = Math.max(result, arrowLeft + arrowRight);
68+
69+
return Math.max(arrowLeft, arrowRight);
70+
}
71+
}

0 commit comments

Comments
 (0)