/*
* 将路径上的节点添加到队列中去
*/
public static boolean LCAPath(Node root,int x,ArrayList<Long> path){
if(root==null)
return false;
path.add(root.element);
if(root.element!=x&&!LCAPath(root.leftChild, x, path)&&!LCAPath(root.rightChild, x, path)){
path.remove(root.element);
return false;
}
return true;
}
上面的函数将从根结点开始的路径放入list中。
/*
* 二叉树求公共祖先(迭代版)
*/
public static Long findLCA(Node root,int x,int y){
ArrayList<Long> path1 =new ArrayList();
ArrayList<Long> path2 =new ArrayList();
//获取到两个结点的路径
LCAPath(root,x, path1);
LCAPath(root,y, path2);
//遍历两条路径
Iterator<Long> ite1=path1.iterator();
Iterator<Long> ite2=path2.iterator();
//当前指针记录相同的结点
Long currentNum=(long) 0;
while(ite1.hasNext()&&ite2.hasNext()){
long i=ite1.next();
long j=ite2.next();
if(i==j){
currentNum=i;
}else{
break;
}
}
return currentNum;
}
下面是递归版,但是效率要低一些,
/*
* 二叉树中求两结点的最近祖先(递归版)
*
*/
public static Node findBtreeLca(Node root,int x,int y){
if(root==null)
return null;
if(root.element==x||root.element==y)
return root;
Node left=findBtreeLca(root.leftChild, x, y);
Node right=findBtreeLca(root.rightChild, x, y);
if(left==null)
return right;
else if(right==null)
return left;
return root;
}