题目: 给定两个节点,求它们在一个普通树中的最小公共祖先。
思路: 采用广度优先遍历找到节点,将所有节点父节点存入哈希表,当找到节点时回溯哈希表实现到树根的路径。找两条路径的交点。
java代码:
class TreeNode{
int val;
ArrayList<TreeNode> children;
}
TreeNode LCA4(TreeNode root,TreeNode p,TreeNode q){
if(root==null||p=null||q==null)
return null;
Queue<TreeNode> currLevel=new LinkedList<TreeNode>();
Queue<TreeNode> nextLevel=new LinkedList<TreeNode>();
currLevel.offer(root);
Queue<TreeNode> pp=new LinkedList<TreeNode>();
Queue<TreeNode> qq=new LinkedList<TreeNode>();
HashMap<TreeNode,TreeNode> backTracking=new HashMap<TreeNode,TreeNode>();
while(!currLevel.isEmpty()){
while(!currLevel.isEmpty()){
nextLevel=new LinkedList<TreeNode>();
TreeNode node=currLevel.poll();
for(TreeNode child: node.children){
backTracking.put(child,node);
if(child==p){
addParent(pp,p,backTracking);
}else if(child==q){
addParent(qq,q,backTracking);
}
if(!pp.isEmpty()&&!qq.isEmpty()){
return getLCA(pp,qq);
}else{
nextLevel.offer(child);
}
}
}
currLevel=nextLevel;
}
return null;
}
void addParent(Queue<TreeNode> Que,TreeNode q,HashMap<TreeNode,TreeNode> bt){
TreeNode parent=bt.get(q);
while(parent!=null){
Que.addFirst(parent);
parent=bt.get(parent);
}
}
TreeNode getLCA(Queue<TreeNode> pp,Queue<TreeNode> qq){
TreeNode result=null;
while(!pp.isEmpty()&&!qq.isEmpty()){
TreeNode pParent=pp.poll();
TreeNode qParent=qq.poll();
if(pParent==qParent){
result=pParent;
}else{
break;
}
}
return reault;
}