class Node{
Integer data;
Node left;
Node right;
public Node(int data) {
this.data = data;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Node node = (Node) o;
return Objects.equals(data, node.data);
}
@Override
public int hashCode() {
return Objects.hash(data);
}
}
方法一:
private static Node findFatherNode(Node root, Node o1, Node o2) {
Map<Node, Node> map = new HashMap<>();
map.put(root, root);
process(root, map);
Set<Node> nodes = new HashSet<>();
Node fatherNode = map.get(o1);
while(!o1.equals(fatherNode)){
nodes.add(o1);
o1 = fatherNode;
fatherNode = map.get(o1);
}
nodes.add(fatherNode);
while(!nodes.contains(o2)){
o2 = map.get(o2);
}
return o2;
}
private static void process(Node root, Map<Node, Node> map) {
if(root == null){
return;
}
map.put(root.left, root);
map.put(root.right, root);
process(root.left, map);
process(root.right, map);
}
方法二:
private static Node findFatherNode2(Node root, Node o1, Node o2) {
if(root == null || root.equals(o1) || root.equals(o2)){
return root;
}
Node leftNode = findFatherNode2(root.left, o1, o2);
Node rightNode = findFatherNode2(root.right, o1, o2);
if(leftNode != null && rightNode != null){
return root;
}
return leftNode != null ? leftNode : rightNode;
}