-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMaxDistance.java
More file actions
48 lines (39 loc) · 1.15 KB
/
MaxDistance.java
File metadata and controls
48 lines (39 loc) · 1.15 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
package class01;
/**
* @author pacai
* @version 1.0
* 求二叉树两个结点的最大距离
*/
public class MaxDistance {
public static class Node<T> {
T data;
Node<T> left;
Node<T> right;
public Node(T data) {
this.data = data;
}
}
private static class Info {
int height;
int maxDistance;
public Info(int height, int maxDistance) {
this.height = height;
this.maxDistance = maxDistance;
}
}
public static <T> int maxDistance(Node<T> head) {
return process(head).maxDistance;
}
public static <T> Info process(Node<T> X) {
if (X == null) {
return new Info(0, 0);
}
Info leftInfo = process(X.left);
Info rightInfo = process(X.right);
int height = Math.max(leftInfo.height, rightInfo.height) + 1;
//动态规划
int maxDistance = Math.max(Math.max(leftInfo.maxDistance, rightInfo.maxDistance),
leftInfo.height + rightInfo.height + 1);
return new Info(height, maxDistance);
}
}