【题目】给定二叉树的两个二节点node1,node2,找出这两个节点的最低公共祖先节点
【思路】
2种情况
1.node1是node2的祖先节点或者node2是node1的祖先节点
2.node1和node2属于不同的子树
【方法一】利用递归
private Node lowestCommonAncestor(Node head, Node o1, Node o2){
if (head == null || o1 == head || o2 == head){
return head;
}
Node left = lowestCommonAncestor(head.left, o1, o2);
Node right = lowestCommonAncestor(head.right, o1, o2);
if (null != left && null != right){
return head;
}
return left != null ? left : right;
}
【方法二】利用hashmap,将所有节点存入map中,key是每个节点,value是每个节点的父节点,取node1开始回溯,向上遍历,一直到根节点,得到所有节点,放入set中,开始回溯node2,向上遍历,并判断遍历到的节点是否已经存在于set中,遇到的第一个存在的节点就是最低公共祖先节点
private void setMap(Node head, HashMap<Node, Node> fatherMap){
if (null == head){
return;
}
if (null != head.left){
fatherMap.put(head.left, head);
}
if (null != head.right){
fatherMap.put(head.right, head);
}