File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 11public class HouseRobberIII {
22
3+ /**
4+ * 效率堪忧,耗时1000ms
5+ */
36 public int rob (TreeNode root ) {
47 return rob (root , true );
58 }
@@ -19,4 +22,25 @@ private int rob(TreeNode root, boolean rob) {
1922 return rob (root .left , true ) + rob (root .right , true );
2023 }
2124 }
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+
2246}
Original file line number Diff line number Diff line change 44
55public class Main {
66
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 };
2015 }
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 ;
2222 }
2323
2424 public static void main (String [] args ) {
You can’t perform that action at this time.
0 commit comments