描述
The thief has found himself a new place for his thievery again. There is only one entrance to this area, called the “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 forms a binary tree”. It will automatically contact the police if two directly-linked houses were broken into on the same night.
Determine the maximum amount of money the thief can rob tonight without alerting the police.
Example 1:
1 | 3 |
Maximum amount of money the thief can rob = 3 + 3 + 1 = 7.
Example 2:
1 | 3 |
Maximum amount of money the thief can rob = 4 + 5 = 9.
分析
这道题是House Robber的第三个版本,第一个版本是从一个序列中选择一些元素,使得和最大,但不能选择相邻的元素。第二个版本给定的序列是一个环,也就是说第一个不能和最后一个同时选。这道题的思路跟前面的版本是一致的,只不过跟树结合起来了,需要结合树的深度遍历的方式。
节点分窃取和不窃取两种情况,因此返回值是一个pair对象,包括两个值,第一个值是窃取了该节点的最大值,另外一个是不窃取该节点的最大值,在这两个值中取最大值。如果窃取了该节点,那么不能取该节点的左右子节点,值为:left.second+right.second+root->val,如果没有窃取该节点,值为左右节点能够窃取的最大值之和,值为:max(left.first, left.second)+max(right.first, right.second)。
解决方案1(C++)
1 | /** |
相关问题
(E) House Robber
(M) House Robber II