File tree 2 files changed +55
-0
lines changed
solution/337. House Robber III
2 files changed +55
-0
lines changed Original file line number Diff line number Diff line change
1
+ /**
2
+ * Definition for a binary tree node.
3
+ * public class TreeNode {
4
+ * int val;
5
+ * TreeNode left;
6
+ * TreeNode right;
7
+ * TreeNode(int x) { val = x; }
8
+ * }
9
+ */
10
+ class Solution {
11
+
12
+ Map <TreeNode , Integer > memo = new HashMap <>();
13
+
14
+ public int rob (TreeNode root ) {
15
+ if (root == null ) return 0 ;
16
+
17
+ if (memo .containsKey (root ))
18
+ return memo .get (root );
19
+
20
+ int do_it = root .val
21
+ + (root .left == null ? 0 : rob (root .left .left ) + rob (root .left .right ))
22
+ + (root .right == null ? 0 : rob (root .right .left ) + rob (root .right .right ));
23
+
24
+ int not_do = rob (root .left ) + rob (root .right );
25
+
26
+ int res = Math .max (do_it , not_do );
27
+ memo .put (root , res );
28
+ return res ;
29
+ }
30
+ }
Original file line number Diff line number Diff line change
1
+ /**
2
+ * Definition for a binary tree node.
3
+ * public class TreeNode {
4
+ * int val;
5
+ * TreeNode left;
6
+ * TreeNode right;
7
+ * TreeNode(int x) { val = x; }
8
+ * }
9
+ */
10
+ class Solution {
11
+ public int rob (TreeNode root ) {
12
+ int [] res = solution (root );
13
+ return Math .max (res [0 ], res [1 ]);
14
+ }
15
+
16
+ private int [] solution (TreeNode root ) {
17
+ if (root == null ) return new int []{0 , 0 };
18
+ int [] left = solution (root .left );
19
+ int [] right = solution (root .right );
20
+
21
+ int rob = root .val + left [1 ] + right [1 ];
22
+ int notRob = Math .max (left [0 ], left [1 ]) + Math .max (right [0 ], right [1 ]);
23
+ return new int []{rob , notRob };
24
+ }
25
+ }
You can’t perform that action at this time.
0 commit comments