forked from DengWangBao/Leetcode-Java
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDiameterOfBinaryTree.java
More file actions
31 lines (25 loc) · 707 Bytes
/
DiameterOfBinaryTree.java
File metadata and controls
31 lines (25 loc) · 707 Bytes
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
public class DiameterOfBinaryTree {
/**
* 这题和 124. Binary Tree Maximum Path Sum比较像
*/
public int diameterOfBinaryTree(TreeNode root) {
if (root == null) {
return 0;
}
return dfs(root, new int[1]) - 1;
}
/**
* len表示带上root的最大深度
*/
private int dfs(TreeNode root, int[] len) {
if (root == null) {
return 0;
}
int[] lt = new int[1];
int[] rt = new int[1];
int left = dfs(root.left, lt);
int right = dfs(root.right, rt);
len[0] = Math.max(lt[0], rt[0]) + 1;
return Math.max(Math.max(left, right), lt[0] + rt[0] + 1);
}
}