【题目】给定一个二叉树的头节点head,以及这棵树中的两个节点o1和o2,请返回o1和o2的最近公共祖先节点。
【进阶】如果查询两个节点的最近公共祖先的操作十分频繁,想法让单条查询的查询时间减少。
public class LowestAncestor {
public static class Node {
public int value;
public Node left;
public Node right;
public Node(int value) {
this.value = value;
}
}
public static Node getLowestAncestor(Node head, Node o1, Node o2) {
if (head == null || head == o1 || head == o2) {
return head;
}
Node left = getLowestAncestor(head.left, o1, o2);
Node right = getLowestAncestor(head.right, o1, o2);
if (left != null && right != null) {
return head;
}
return left == null ? right : left;
}
public static class Record {
public Map<Node, Node> map;
public Record(Node head) {
map = new HashMap<Node, Node>();
if (head != null) {
map.put(head, null);
setMap(head);
}
}
public void setMap(Node head) {
if (head == null) {
return;
}
if (head.left != null) {
map.put(head.left, head);
}
if (head.right != null) {
map.put(head.right, head);
}
setMap(head.left);
setMap(head.right);
}
public Node query(Node o1, Node o2) {
Set<Node> set = new HashSet<>();
while (map.containsKey(o1)) {
set.add(o1);
o1 = map.get(o1);
}
while (!set.contains(o2)) {
o2 = map.get(o2);
}
return o2;
}
}
}