Skip to content
Discussion options

You must be logged in to vote
class Solution {
    Map<TreeNode, Integer> mem = new HashMap<>();
    public int rob(TreeNode root) {
        if(root==null) return 0;
        if(mem.containsKey(root)) return mem.get(root);

        int doVal = root.val + (root.left == null ? 0 : rob(root.left.left) + rob(root.left.right))
        + (root.right == null ? 0 : rob(root.right.left) + rob(root.right.right));
        int notDoVal = rob(root.left) + rob(root.right);
        int res = Math.max(doVal, notDoVal);
        mem.put(root, res);
        return res;
    }
}

Replies: 1 comment 1 reply

Comment options

You must be logged in to vote
1 reply
@taotie6
Comment options

Answer selected by taotie6
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants