您的位置:首页 > 其它

二叉树系列---在二叉树中找到两个节点的最近公共祖先

2016-11-04 02:11 651 查看

题目

给定一颗二叉树的头结点,和这颗二叉树中2个节点n1和n2,求这两个节点的最近公共祖先;

思路

利用后序遍历实现;

对于当前节点cur,如果节点为null或者等于n1或n2中的一个,则直接返回cur;

先处理左右子树,左子树返回left,右子树返回right;判断left和right;

1)left和right均为null,说明以cur为根的树上没发现n1和n2;

2)left和right均不为null,说明在左子树上发现了n1或n2,在右子树上也发现了n1或n2,cur为n1和n2的首次相遇节点,则直接返回cur;

3)left和right中一个null,另一个不为null,说明不为空的节点是n1和n2的其中一个,或者是n1和n2的最近公共祖先;则返回不为空的节点;

实现

package binary_tree;

/**
* 求2个节点的最近公共祖先节点
* @author fxx
*
*/
public class LowestAncestor {

/*求解n1和n1的最近公共祖先
*
* 利用后序遍历求解
*/
public Node getLowestAncestor(Node head,Node n1,Node n2){
if(head==null || head==n1 || head==n2){
return head;
}

//先遍历左右子树,左右子树的返回为left和right;然后判断left和right请情况
Node left=getLowestAncestor(head.left,n1,n2);
Node right=getLowestAncestor(head.right,n1,n2);

/*左和右都不为null---说明在左子树中发现过n1或n2,
* 在右子树上也发现过n1或n2,并且n1和n2在当前节点首次相遇
*/
if(left!=null && right!=null){
return head;
}

/*左和右中一个不为null,另一个为null,
* 说明不为null的节点是n1或n2中的一个,或者是n1和n2的最近祖先;
* 直接返回;
*/
if(left!=null){
return left;
}
if(right!=null){
return right;
}

//左和右均为null,没有发现n1和n2;
return null;
}

}


改进1

建立一个结构hashMap:每个节点对应的父节点;

查询公共祖先的过程:

先查询hashMap,将n1和n1的祖先节点找出并放入另一个哈希表A中,从n2开始向上移动,如果在A中发现了当前节点,则返回,否则向上移动;

package binary_tree;

import java.util.HashMap;
import java.util.HashSet;

public class LowestAncestor2 {

private HashMap<Node,Node> map;//存放每个节点对应的父节点

public LowestAncestor2(Node head){
map=new HashMap<Node,Node>();
if(head!=null){
map.put(head, null);
}
setMap(head);
}

private 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 getLowestAncestor(Node root,Node n1,Node n2){
HashSet<Node> set=new HashSet<Node>();
while(map.containsKey(n1)){
set.add(n1);
n1=map.get(n1);
}
while(!set.contains(n2)){
n2=map.get(n2);
}
return n2;
}
}


测试

/**
* @param args
*/
public static void main(String[] args) {
LowestAncestor LA=new LowestAncestor();
Node head=LA.buildTree();
Node node=LA.getLowestAncestor(head, head.left.left,head.right.right.right);
System.out.println(node.value);

}

private Node buildTree(){
Node head=new Node(1);
head.left=new Node(2);
head.right=new Node(3);

head.left.left=new Node(4);
head.left.right=new Node(5);

head.right.left=new Node(6);
head.right.right=new Node(7);

head.right.right.right=new Node(8);

return head;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  二叉树
相关文章推荐