思路:
先找出所有元素的父节点,使用HashMap进行存储。
找出一个节点的父节点的结合。使用HashSet进行存储。
然后另外一个节点就从下到上依次找每个父节点,看另一个父节点集合中是否包含此节点,如果包含就输出。
public static NodeTwo findLowNode(NodeTwo head,NodeTwo node1,NodeTwo node2) {
HashMap<NodeTwo,NodeTwo> fatherMap = new HashMap<NodeTwo,NodeTwo>();
//所有节点的父节点都有了,只有头结点没有加进去,头结点的父节点就是自己
fatherMap.put(head,head);
process(fatherMap,head);
HashSet<NodeTwo> set1 = new HashSet<NodeTwo>();
NodeTwo cur = node1;
//将一个节点的父节点全部找出。
while(cur!=fatherMap.get(cur)){
set1.add(cur);
cur = fatherMap.get(cur);
}
set1.add(head);
cur = node2;
//另一个节点的父节点从下到上进行查询是否包含即可。
while(cur!=fatherMap.get(cur)) {
if(set1.contains(cur)) {
return cur;
}
cur = fatherMap.get(cur);
}
return head;
}
//找出所有节点的父节点
public static void process(HashMap<NodeTwo,NodeTwo> fatherMap,NodeTwo head) {
if(head == null) {
return ;
}
fatherMap.put(head.left, head);
fatherMap.put(head.right,head);
process(fatherMap,head.left);
process(fatherMap,head.right);
}