题目

思路
- 根据p、q在左右子树的情况区分,所以先获取子树的情况,再判断当前节点,是后序遍历
- 树的后序遍历,是从下至上遍历的,所以获取的节点会是深度最大的节点
- 设计一个递归函数,若找到p或q,则返回对应节点,对于任一节点,p、q在左右子树的情况有4种
- p或q都不在 左右子树,返回 null
- p或q不在右子树,返回左孩子
- p或q不在左子树,返回右孩子
- 左子树和右子树都能找到p或q,返回当前节点,且说明当前节点是最近公共祖先
代码
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
if(root == null){
return root;
}
TreeNode left=lowestCommonAncestor(root.left,p,q);
TreeNode right=lowestCommonAncestor(root.right,p,q);
if(root == p || root == q){
return root;
}
if(left == null && right == null){
return null;
}else if(left == null){
return right;
}else if(right == null){
return left;
}
return root;
}
参考链接
面试题68 - II. 二叉树的最近公共祖先(后序遍历 DFS ,清晰图解