-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDiameterOfBTree.java
More file actions
51 lines (43 loc) · 908 Bytes
/
DiameterOfBTree.java
File metadata and controls
51 lines (43 loc) · 908 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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) {
val = x;
}
}
class Result {
int length;
int max;
}
public class DiameterOfBTree {
public int diameterOfBinaryTree(TreeNode root) {
Result rootResult = getResult(root);
return rootResult.max;
}
private Result getResult(TreeNode root) {
Result r = new Result();
if (root == null) {
r.length = 0;
r.max = 0;
return r;
}
if (root.left == null && root.right == null) {
r.length = 1;
r.max = 1;
return r;
}
Result left = getResult(root.left);
Result right = getResult(root.right);
int max = Math.max(left.max, right.max);
if (left.length + right.length + 2 > max) {
r.length = Math.max(left.length, right.length)+1;
r.max = left.length + right.length + 2;
return r;
} else {
r.length = Math.max(left.length, right.length)+1;
r.max = max;
return r;
}
}
}