House Robber III
ID:337
Last updated
ID:337
Last updated
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.
Starting from root, if root is null, return 0; else, sum the result of root.left and root.right
Since adjacent node cannot be robbed:
result of root.left = root.left.left+root.left.right /
root.right = root.right.left+root.right.right
Since the result from root is result of root.left+result of root.right, we need to add the value of root as well.
Pick the max from (result from root, result from left child, result from right child)
Use HashMap to store the seen node result, so that do not need to calculate the result from a seen node to save time cost