File tree Expand file tree Collapse file tree 1 file changed +56
-0
lines changed
src/topinterviewquestions Expand file tree Collapse file tree 1 file changed +56
-0
lines changed Original file line number Diff line number Diff line change
1
+ package topinterviewquestions ;
2
+
3
+ public class Problem_0687_LongestUnivaluePath {
4
+
5
+ public static class TreeNode {
6
+ public int val ;
7
+ public TreeNode left ;
8
+ public TreeNode right ;
9
+
10
+ public TreeNode (int v ) {
11
+ val = v ;
12
+ }
13
+ }
14
+
15
+ public static int longestUnivaluePath (TreeNode root ) {
16
+ if (root == null ) {
17
+ return 0 ;
18
+ }
19
+ return process (root ).max - 1 ;
20
+ }
21
+
22
+ // 建设以x节点为头的树,返回两个信息
23
+ public static class Info {
24
+ // 在一条路径上:要求每个节点通过且只通过一遍
25
+ public int len ; // 路径必须从x出发且只能往下走的情况下,路径的最大距离
26
+ public int max ; // 路径不要求必须从x出发的情况下,整棵树的合法路径最大距离
27
+
28
+ public Info (int l , int m ) {
29
+ len = l ;
30
+ max = m ;
31
+ }
32
+ }
33
+
34
+ private static Info process (TreeNode x ) {
35
+ if (x == null ) {
36
+ return new Info (0 , 0 );
37
+ }
38
+ TreeNode l = x .left ;
39
+ TreeNode r = x .right ;
40
+ Info linfo = process (l );
41
+ Info rinfo = process (r );
42
+ int len = 1 ;
43
+ if (l != null && l .val == x .val ) {
44
+ len = linfo .len + 1 ;
45
+ }
46
+ if (r != null && r .val == x .val ) {
47
+ len = Math .max (len , rinfo .len + 1 );
48
+ }
49
+ int max = Math .max (Math .max (linfo .max , rinfo .max ), len );
50
+ if (l != null && r != null && l .val == x .val && r .val == x .val ) {
51
+ max = Math .max (max , linfo .len + rinfo .len + 1 );
52
+ }
53
+ return new Info (len , max );
54
+ }
55
+
56
+ }
You can’t perform that action at this time.
0 commit comments