package com.Tree;
import java.util.LinkedList;
public class CommonFather {
/**
* 题目描述:给定一棵二叉树,要求找到其中任意两节点的最小公共父节点。
* 思路:最原始的方法,从根开始,分别寻找从根节点到每个目标节点的路径,然后比较 两条路径,找到最小的公共父节点。
* @param args
* @author Adai
*/
private LinkedList<TNode> path;
private static class TNode{
int data;
TNode leftchild;
TNode rightchild;
public TNode(int da){
this.data=da;
this.leftchild=null;
this.rightchild=null;
}
}
private TNode root;
public CommonFather(int[] list){
TNode curr=null;
for(int i=0;i<list.length;i++){
TNode now=new TNode(list[i]);
if(i==0){
root=now;
curr=root;
}else{
curr=root;
while(curr!=null){
if(curr.data<now.data){
if(curr.rightchild!=null){
curr=curr.rightchild;
}else{
curr.rightchild=now;
break;
}
}else{
if(curr.leftchild!=null){
curr=curr.leftchild;
}else{
curr.leftchild=now;
break;
}
}
}
}
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
int[] list={5,4,6,3,7,2,8,1,9};
CommonFather cf=new CommonFather(list);
TNode tar=cf.FindCommonFather(cf.root, 3, 7);
System.out.println(tar.data);
}
public TNode FindCommonFather(TNode root,int t1,int t2){
if(root==null) return null;
path=new LinkedList<TNode>();
LinkedList<TNode> set=new LinkedList<TNode>();
TNode cur=root;
if(FindTNode(cur,t1)){
while(!path.isEmpty()){
TNode now=path.pop();
set.push(now);
System.out.println(now.data);
}
}else{
return null;
}
path.clear();
cur=root;
LinkedList<TNode> guest=new LinkedList<TNode>();
if(FindTNode(cur,t2)){
TNode cf=null;
while(!path.isEmpty()){
TNode now=path.pop();
System.out.println("2:"+now.data);
guest.push(now);
}
}else{
return null;
}
TNode ret=null;
while(!set.isEmpty()&&!guest.isEmpty()){
TNode se=set.pop();
TNode ge=guest.pop();
if(se.equals(ge)){
ret=se;
}else{
return ret;
}
}
return null;
}
private boolean FindTNode(TNode nowroot,int target){
path.push(nowroot);
if(nowroot==null){
path.pop();
return false;
}else if(nowroot.data==target){
return true;
}else{
if(FindTNode(nowroot.leftchild,target)){
return true;
}
if(FindTNode(nowroot.rightchild,target)){
return true;
}
path.pop();
return false;
}
}
}