File tree Expand file tree Collapse file tree 2 files changed +38
-14
lines changed Expand file tree Collapse file tree 2 files changed +38
-14
lines changed Original file line number Diff line number Diff line change 1
1
public class HouseRobberIII {
2
2
3
+ /**
4
+ * 效率堪忧,耗时1000ms
5
+ */
3
6
public int rob (TreeNode root ) {
4
7
return rob (root , true );
5
8
}
@@ -19,4 +22,25 @@ private int rob(TreeNode root, boolean rob) {
19
22
return rob (root .left , true ) + rob (root .right , true );
20
23
}
21
24
}
25
+
26
+ /**
27
+ * 优化写法如下,耗时1ms
28
+ */
29
+ public int rob2 (TreeNode root ) {
30
+ int [] val = helper (root );
31
+ return Math .max (val [0 ], val [1 ]);
32
+ }
33
+
34
+ private int [] helper (TreeNode node ) {
35
+ if (node == null ) {
36
+ return new int []{0 ,0 };
37
+ }
38
+ int [] left = helper (node .left );
39
+ int [] right = helper (node .right );
40
+ int [] value = new int [2 ];
41
+ value [0 ] = Math .max (left [0 ], left [1 ]) + Math .max (right [0 ], right [1 ]);
42
+ value [1 ] = node .val + left [0 ] + right [0 ];
43
+ return value ;
44
+ }
45
+
22
46
}
Original file line number Diff line number Diff line change 4
4
5
5
public class Main {
6
6
7
- public int kthSmallest (TreeNode root , int k ) {
8
- Stack <TreeNode > stack = new Stack <>();
9
- while (!stack .isEmpty () || root != null ) {
10
- if (root != null ) {
11
- stack .push (root );
12
- root = root .left ;
13
- } else {
14
- root = stack .pop ();
15
- if (--k == 0 ) {
16
- return root .val ;
17
- }
18
- root = root .right ;
19
- }
7
+ public int rob (TreeNode root ) {
8
+ int [] val = helper (root );
9
+ return Math .max (val [0 ], val [1 ]);
10
+ }
11
+
12
+ private int [] helper (TreeNode node ) {
13
+ if (node == null ) {
14
+ return new int []{0 ,0 };
20
15
}
21
- return 0 ;
16
+ int [] left = helper (node .left );
17
+ int [] right = helper (node .right );
18
+ int [] value = new int [2 ];
19
+ value [0 ] = Math .max (left [0 ], left [1 ]) + Math .max (right [0 ], right [1 ]);
20
+ value [1 ] = node .val + left [0 ] + right [0 ];
21
+ return value ;
22
22
}
23
23
24
24
public static void main (String [] args ) {
You can’t perform that action at this time.
0 commit comments