-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHouseRobberIII.java
More file actions
67 lines (55 loc) · 1.96 KB
/
Copy pathHouseRobberIII.java
File metadata and controls
67 lines (55 loc) · 1.96 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
/*
337. 打家劫舍 III
在上次打劫完一条街道之后和一圈房屋后,小偷又发现了一个新的可行窃的地区。这个地区只有一个入口,我们称之为“根”。 除了“根”之外,每栋房子有且只有一个“父“房子与之相连。一番侦察之后,聪明的小偷意识到“这个地方的所有房屋的排列类似于一棵二叉树”。 如果两个直接相连的房子在同一天晚上被打劫,房屋将自动报警。
计算在不触动警报的情况下,小偷一晚能够盗取的最高金额。
示例 1:
输入: [3,2,3,null,3,null,1]
3
/ \
2 3
\ \
3 1
输出: 7
解释: 小偷一晚能够盗取的最高金额 = 3 + 3 + 1 = 7.
示例 2:
输入: [3,4,5,1,3,null,1]
3
/ \
4 5
/ \ \
1 3 1
输出: 9
解释: 小偷一晚能够盗取的最高金额 = 4 + 5 = 9.
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/house-robber-iii
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
*/
package dp;
public class HouseRobberIII {
public static class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) {
val = x;
}
}
public static int rob(TreeNode root) {
return rootHepler(root).val;
}
public static TreeNode rootHepler(TreeNode node) {
if (node == null) {
TreeNode newNode = new TreeNode(0);
return rootHepler(newNode);
}
if (node.left == null && node.right == null) {
node.left = new TreeNode(0);
node.right = new TreeNode(0);
return node;
}
node.left = rootHepler(node.left);
node.right = rootHepler(node.right);
node.val = Math.max(node.left.val + node.right.val, node.val + node.left.left.val + node.left.right.val + node.right.left.val + node.right.right.val);
return node;
}
}