[LeetCode] 337. House Robber III

题目内容

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:

Input: [3,2,3,null,3,null,1]

     3
    / \
   2   3
    \   \ 
     3   1

Output: 7 
Explanation: Maximum amount of money the thief can rob = 3 + 3 + 1 = 7.
Example 2:

Input: [3,4,5,1,3,null,1]

     3
    / \
   4   5
  / \   \ 
 1   3   1

Output: 9
Explanation: Maximum amount of money the thief can rob = 4 + 5 = 9.

题目思路

这道题目的思路在于,我们需要考虑两种可能然后根据这两种可能性进行递归。第一种,抢劫目前读取的根节点(当前节点),那么这种情况下的数值就是当前节点的数值+左右子树的子树最大数值;第二种,不抢劫当前根节点,那么这种情况下的数值就是左右两个子树的最大值。最后对于两者进行比较,取最大数值即可。


程序代码

上一篇:leetcode 337. 打家劫舍iii


下一篇:leetcode 337. 打家劫舍 III java