leetcode House Robber III

题目链接

动态规划,可以把空间优化到线性时间

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
   HashMap<TreeNode, Integer> mapNot=new HashMap<TreeNode, Integer>();
    HashMap<TreeNode, Integer> mapDo=new HashMap<TreeNode, Integer>();

    public int rob(TreeNode root) {
        if(root==null)
        {
            return 0;
        }
        help(root);
        return Math.max(mapNot.get(root), mapDo.get(root));
    }

    public void help(TreeNode root)
    {
        Integer notRob=0;
        Integer rob=0;
        if(root.left!=null)
        {
            help(root.left);
            notRob+=Math.max(mapNot.get(root.left), mapDo.get(root.left));
            rob+=mapNot.get(root.left);
        }
        if(root.right!=null)
        {
            help(root.right);
            notRob+=Math.max(mapNot.get(root.right), mapDo.get(root.right));
            rob+=mapNot.get(root.right);
        }
        rob+=root.val;
        mapNot.put(root, notRob);
        mapDo.put(root,rob);

    }
}

你可能感兴趣的:(leetcode House Robber III)