File tree Expand file tree Collapse file tree 1 file changed +44
-0
lines changed Expand file tree Collapse file tree 1 file changed +44
-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() {}
8
+ * TreeNode(int val) { this.val = val; }
9
+ * TreeNode(int val, TreeNode left, TreeNode right) {
10
+ * this.val = val;
11
+ * this.left = left;
12
+ * this.right = right;
13
+ * }
14
+ * }
15
+ */
16
+ class Solution {
17
+ Map<TreeNode,Integer> map=new HashMap<>();
18
+ public int rob(TreeNode root) {
19
+ if(root==null){
20
+ return 0;
21
+ }
22
+ if(map.containsKey(root)){
23
+ return map.get(root);
24
+ }
25
+
26
+ int sum=root.val;
27
+
28
+ if(root.left!=null){
29
+ sum+=rob(root.left.left);
30
+ sum+=rob(root.left.right);
31
+ }
32
+
33
+ if(root.right!=null){
34
+ sum+=rob(root.right.left);
35
+ sum+=rob(root.right.right);
36
+ }
37
+
38
+ int next_sum=rob(root.left)+rob(root.right);
39
+
40
+ int res=Math.max(sum,next_sum);
41
+ map.put(root,res);
42
+ return res;
43
+ }
44
+ }
You can’t perform that action at this time.
0 commit comments