337. 打家劫舍 III(逐句解释代码)

package LeetCode.OneToFiveHundred;

import LeetCode.TreeNode;

import java.util.HashMap;

public class ThreeHundredsAndThirtySeven {
    public int rob(TreeNode root) {
        HashMap<TreeNode, Integer> hashMap = new HashMap<>();
        return helper(root, hashMap);
    }
    private int helper(TreeNode root, HashMap<TreeNode, Integer> hashMap){
        if (root == null) return 0;
        // 检查在 map 中是否已经算过当前的层数了
        if (hashMap.containsKey(root)) return hashMap.get(root);
        int money = root.val;
        // 计算孙子节点的值,直接统计
        if (root.left != null)
            money += (helper(root.left.left, hashMap) + helper(root.left.right, hashMap));
        if (root.right != null)
            money += (helper(root.right.left, hashMap) + helper(root.right.right, hashMap));
        // 用爷爷节点的值根儿子结点的值进行比较,此处爷爷节点包括孙子节点以及后序的所有可能节点,儿子节点相同
        int ans = Math.max(money, helper(root.left, hashMap) + helper(root.right, hashMap));
        // 将结果存储,记忆化,减少时间消耗
        hashMap.put(root,ans);
        return ans;
    }
}

你可能感兴趣的:(LeetCode,Java,spark,二叉树)