DEV Community

codingpineapple
codingpineapple

Posted on

LeetCode 337. House Robber III (javascript solution)

Description:

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.

Solution:

Time Complexity : O(n)
Space Complexity: O(n)

 var rob = function(root) {
    // Choose between using values at root + grandchildren (current) or using values from children (next)
    const { current, next } = traverse(root);

    return Math.max(current, next);
};

function traverse(root) {
    // If there is not root ther is no root value or grandchildren values (current) and there are also no children values (next)
    if (!root) {
        return { current: 0, next: 0 };
    }

    // Get values for children
    const left = traverse(root.left);
    const right = traverse(root.right);

    // Value if we include the root node in our robbing path
    const current = root.val + left.next + right.next;

    // Max Value if we include the children in our robbing path
    const next = Math.max(left.current, left.next) + Math.max(right.current, right.next);

    return { current, next };
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)