其他分享
首页 > 其他分享> > 力扣-337-打家劫舍II

力扣-337-打家劫舍II

作者:互联网

动态规划思想,对于当前节点,只有取或不取两种情况,所以有:

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

    public int rob(TreeNode root) {
        dfs(root);
        return Math.max(f.getOrDefault(root, 0), g.getOrDefault(root, 0));
    }

    public void dfs(TreeNode root) {
        if(root == null) return ;
        //后序遍历
        dfs(root.left);
        dfs(root.right);
        
        //被选中时         f(node) = g(left) + g(right) + node.val
        //未被选中时    g(node) = max(f(left), g(left)) + max(f(right), g(right))
        //最终结果是    result = max(f(root), g(root))
        f.put(root, root.val + g.getOrDefault(root.left, 0) + g.getOrDefault(root.right, 0));
        g.put(root, Math.max(f.getOrDefault(root.left, 0), g.getOrDefault(root.left, 0)) + 
                Math.max(f.getOrDefault(root.right, 0), g.getOrDefault(root.right, 0)));
    }
}

 

这里给出已知Key求Value的两种做法:

default V getOrDefault(Object key, V defaultValue) {
    V v;
    return (((v = get(key)) != null) || containsKey(key))? v: defaultValue;
}

标签:node,II,right,max,337,力扣,getOrDefault,root,left
来源: https://www.cnblogs.com/xiazhenbin/p/13784254.html