File tree 1 file changed +71
-0
lines changed 1 file changed +71
-0
lines changed Original file line number Diff line number Diff line change
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
+ }
You can’t perform that action at this time.
0 commit comments