337. House Robber III二叉树上的抢劫题

时间:2023-04-13 10:07:14

[抄题]:

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.

[暴力解法]:

时间分析:

空间分析:

[优化后]:

时间分析:

空间分析:

[奇葩输出条件]:

[奇葩corner case]:

[思维问题]:

知道是dc,不知道具体怎么写。用dc可以新生成数组,不需要别的参数。因为数组里面的元素只有2个,指定一下就行了。

[英文数据结构或算法,为什么不用别的数据结构或算法]:

数组:因为只有偷与否2种状态,left right res都需要在其中比较,所以开空间为2的数组即可

[一句话思路]:

[输入量]:空: 正常情况:特大:特小:程序里处理到的特殊情况:异常情况(不合法不合理的输入):

[画图]:

[一刷]:

[二刷]:

[三刷]:

[四刷]:

[五刷]:

[五分钟肉眼debug的结果]:

[总结]:

用dc可以新生成数组,不需要别的参数。因为数组里面的元素只有2个,指定一下就行了。

[复杂度]:Time complexity: O(n) Space complexity: O(n)

[算法思想:迭代/递归/分治/贪心]:

[关键模板化代码]:

[其他解法]:

[Follow Up]:

[LC给出的题目变变变]:

[代码风格] :

[是否头一次写此类driver funcion的代码] :

[潜台词] :

/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public int rob(TreeNode root) {
//corner case
if (root == null) return 0; //call the robHelper
int[] result = robHelper(root); //compare and return
return Math.max(result[0], result[1]);
} public int[] robHelper(TreeNode root) {
//corner case
if (root == null) return new int[2];
int[] result = new int[2]; //initialization : 2 int[] left and right
int[] left = robHelper(root.left);
int[] right = robHelper(root.right); //define the numbers
//choose root
result[1] = left[0] + root.val + right[0];
//not choose
result[0] = Math.max(left[0], left[1]) + Math.max(right[0], right[1]); //return
return result;
}
}