题目:
给定一个二叉树, 找到该树中两个指定节点的最近公共祖先。
百度百科中最近公共祖先的定义为:“对于有根树 T 的两个节点 p、q,最近公共祖先表示为一个节点 x,满足 x 是 p、q 的祖先且 x 的深度尽可能大(一个节点也可以是它自己的祖先)。”
输入:root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 1 输出:3 解释:节点5
和节点1
的最近公共祖先是节点3
存储父节点法:
将每一个节点的父节点利用 map 存储下来,为 q , p 中任一节点找到他的所有祖先节点存储在集合中(fatherNodes),另一个节点开始向上走,每走一步就判断当前节点是不是在 fatherNodes 中,若存在返回当前节点即可。
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
Map<TreeNode,TreeNode> fatherMap = new HashMap<>();
//将root节点的父节点设置为root
fatherMap.put(root,root);
//存储父节点
fatherNodes(root,fatherMap);
//记录p节点的所有祖先节点
Set<TreeNode> set = new HashSet<TreeNode>();
TreeNode curNode = p;
while(curNode != root){
set.add(curNode);
curNode = fatherMap.get(curNode);
}
//q 节点开始向上跳
curNode = q;
while(curNode != root){
if(set.contains(curNode)){
return curNode;
}else{
curNode = fatherMap.get(curNode);
}
}
return root;
}
public void fatherNodes(TreeNode root,Map<TreeNode,TreeNode> fatherMap){
if(root == null){
return;
}
//存储每个节点的父节点
fatherMap.put(root.left,root);
fatherMap.put(root.right,root);
fatherNodes(root.left,fatherMap);
fatherNodes(root.right,fatherMap);
}
递归法:
分析代码:
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
//对于第一种情况的处理
if(root == null || root== p || root== q){
//直接返回
return root;
}
TreeNode left = lowestCommonAncestor(root.left,p,q);
TreeNode right = lowestCommonAncestor(root.right,p,q);
//对于第二种情况的处理
if(left != null && right != null){
return root;
}
//返回结果要么null,要么就是p,q之一
return left != null ? left : right;
}
最近公共祖先(LCA)总的来说就两种情况:
- p, q 其中一个就是最近公共祖先
- p q 不互为最近公共祖先,需要向上继续跳才能找到
递归法代码的终止条件其实就是对第一种情况的处理,从根节点往下递归的时候,只要遇到q p 之一就结束递归,将其向上回溯,在回溯的过程中处理第二种情况,如果左子树和右子树的返回结果都不为空的话,那么当前递归节点就一定是LCA,因为递归返回结果要么返回空,要么返回q p 之一,left 和 right 都不为空说明q p 在回溯的过程中第一次在此节点相遇。