Skip to content

Commit 655e51c

Browse files
committed
fd
1 parent 48fc7a0 commit 655e51c

File tree

2 files changed

+3
-20
lines changed

2 files changed

+3
-20
lines changed

leetcode/solution/src/HouseRobberIII.java

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,8 @@ private int rob(TreeNode root, boolean rob) {
2525

2626
/**
2727
* 优化写法如下,耗时1ms
28+
* 这里将两种情况都保存下来并返回给上层,避免了多次重复计算
29+
* val[0]表示不rob当前节点,val[1]表示rob当前节点
2830
*/
2931
public int rob2(TreeNode root) {
3032
int[] val = helper(root);

leetcode/src/Main.java

Lines changed: 1 addition & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -6,27 +6,8 @@ public class Main {
66

77
public static class Solution {
88

9-
public int diameterOfBinaryTree(TreeNode root) {
10-
if (root == null) {
11-
return 0;
12-
}
13-
return dfs(root, new int[1]) - 1;
14-
}
15-
16-
private int dfs(TreeNode root, int[] len) {
17-
if (root == null) {
18-
return 0;
19-
}
20-
21-
int[] lt = new int[1];
22-
int[] rt = new int[1];
23-
24-
int left = dfs(root.left, lt);
25-
int right = dfs(root.right, rt);
26-
27-
len[0] = Math.max(lt[0], rt[0]) + 1;
9+
public List<TreeNode> generateTrees(int n) {
2810

29-
return Math.max(Math.max(left, right), lt[0] + rt[0] + 1);
3011
}
3112
}
3213

0 commit comments

Comments
 (0)