给定一个二叉树, 找到该树中两个指定节点的最近公共祖先。
百度百科中最近公共祖先的定义为:“对于有根树 T 的两个节点 p、q,最近公共祖先表示为一个节点 x,满足 x 是 p、q 的祖先且 x 的深度尽可能大(一个节点也可以是它自己的祖先)。
分析:找到指定节点的最近公共祖先,那么首先就要先找到再说,用递归法,终止条件就是要找到该节点或是找不到,并且将该节点返回。
若是有一个节点的左右节点都有值而不是空,那么这个点就是我们想要的。
将这个值点逐层返回即可
参考代码:
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
return sup(root,p,q);
}
private TreeNode sup(TreeNode node,TreeNode p,TreeNode q){
if(node==null) return node;
if(node==p||node==q) return node;
TreeNode left = sup(node.left,p,q);
TreeNode right = sup(node.right,p,q);
if(left!=null&&right!=null) return node;
if(left==null) return right;
return left;
}
