337. House Robber III

和前两题已经关系不大了……是树的dfs,加上一个表track back

 1     public int rob(TreeNode root) {
 2         if(root == null) {
 3             return 0;
 4         }
 5         Map<TreeNode, Integer> a = new HashMap<TreeNode, Integer>();
 6         Map<TreeNode, Integer> b = new HashMap<TreeNode, Integer>();
 7         return Math.max(sum(root, true, a, b), sum(root, false, a, b));
 8     }
 9     
10     private int sum(TreeNode root, boolean visited, Map<TreeNode, Integer> a, Map<TreeNode, Integer> b) {
11         if(root == null) {
12             return 0;
13         }
14         if (!visited && a.containsKey(root)) {
15             return a.get(root);
16         }
17         if (visited && b.containsKey(root)) {
18             return b.get(root);
19         }
20         int left = sum(root.left, false, a, b);
21         int right = sum(root.right, false, a, b);
22         if(visited) {
23             b.put(root, left + right);
24             return left + right;
25         } else {
26             int leftTrue = sum(root.left, true, a, b);
27             int rightTrue = sum(root.right, true, a, b);
28             int sum = Math.max(left + right, leftTrue + rightTrue + root.val);
29             a.put(root, sum);
30             return sum;
31         }
32     }

 

posted @ 2016-06-29 12:16  warmland  阅读(151)  评论(0编辑  收藏  举报