Journal Archive

/**
 * Definition for a binary tree node.
 * function TreeNode(val, left, right) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.left = (left===undefined ? null : left)
 *     this.right = (right===undefined ? null : right)
 * }
 */
/**
 * @param {TreeNode} root
 * @return {number}
 */
var rob = function(root) {
    // Dynamic Programming approach
    const robSubTree = (root, map) => {
        if (!root) return 0;
        if (map.has(root)) return map.get(root);
        
        let money = 0;
        // rob grandchildren of root
        if (root.left) {
            money += robSubTree(root.left.left, map) + robSubTree(root.left.right, map);
        }
        if (root.right) {
            money += robSubTree(root.right.left, map) + robSubTree(root.right.right, map);
        }
        
        money = Math.max(money + root.val, robSubTree(root.left, map) + robSubTree(root.right, map));
        // memoizing to avoid repeated computation
        map.set(root, money);
        
        return money;
    }
    
    return robSubTree(root, new Map());
};

Day 30: Solving one of LeetCode problems

337. House Robber III Difficulty - Medium

The thief has found himself a new place for his thievery again. There is only one entrance to this area, called root.

Besides the root, each house has one and only one parent house. After a tour, the smart thief realized that all houses in this place form a binary tree. It will automatically contact the police if two directly-linked houses were broken into on the same night.

Given the root of the binary tree, return the maximum amount of money the thief can rob without alerting the police.

 

Example 1:

Input: root = [3,2,3,null,3,null,1]
Output: 7
Explanation: Maximum amount of money the thief can rob = 3 + 3 + 1 = 7.
        

Example 2:

Input: root = [3,4,5,1,3,null,1]
Output: 9
Explanation: Maximum amount of money the thief can rob = 4 + 5 = 9.