剑指 Offer 68 - II. 二叉树的最近公共祖先
做题思路·:
终止条件:
当越过叶节点,则直接返回 null ;
当 rootroot 等于 p, q ,则直接返回 root ;
递推工作:
开启递归左子节点,返回值记为 left;
开启递归右子节点,返回值记为 right ;
返回值: 根据 left 和 right,可展开为四种情况;
当 left 和 right 同时为空 :说明 root 的左 / 右子树中都不包含 p,q ,返回 null ;
当 left 和 right 同时不为空 :说明 p,q 分列在 root 的 异侧 (分别在 左 / 右子树),因此 rootroot 为最近公共祖先,返回 root;
当 left 为空 ,right 不为空 :p,q 都不在 root 的左子树中,直接返回 right 。具体可分为两种情况:
p,q 其中一个在 root的 右子树 中,此时 right 指向 p(假设为 p );
p,q 两节点都在 root 的 右子树 中,此时的 right指向 最近公共祖先节点 ;
当 left 不为空 , right 为空 :与情况 3. 同理;
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
//递归终止条件
if(root==null||root==p||root==q){
return root;
}
TreeNode left1=lowestCommonAncestor(root.left,p,q);
TreeNode right1=lowestCommonAncestor(root.right,p,q);
if(right1==null&&left1==null) return null;
//if(right1!=null||right1!=null) return root;
if(left1==null&&right1!=null) return right1;//此种情况说明都在右子树中
if(left1!=null&&right1==null) return left1;
return root; //right1!=null||right1!=null
}
}
剑指 Offer 68 - I. 二叉搜索树的最近公共祖先
方法一:未利用二叉搜索树的性质去做题即普通二叉树的最近公共祖先做法
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
if(root==null||root==p||root==q){
return root;
}
TreeNode left1=lowestCommonAncestor(root.left,p,q);
TreeNode right1=lowestCommonAncestor(root.right,p,q);
if(right1==null&&left1==null) return null;
if(left1==null&&right1!=null) return right1;
if(left1!=null&&right1==null) return left1;
return root;
}
}
方法二:
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
if(root.val<p.val&&root.val<q.val){
return lowestCommonAncestor(root.right,p,q);
}else if(root.val>p.val&&root.val>q.val){
return lowestCommonAncestor(root.left,p,q);
}else{
return root;
}
}
}