[抄题]:node
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:ide
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.
[暴力解法]:优化
时间分析:this
空间分析:spa
[优化后]:debug
时间分析:code
空间分析:
[奇葩输出条件]:
[奇葩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; } }