88.Lowest Common Ancestor
Last updated
Last updated
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode A, TreeNode B) {
if(root==null || root==A || root==B){//当前节点为空或者是AB其中一个就返回当前节点
return root;
}
//Divided
TreeNode left=lowestCommonAncestor(root.left,A,B);
TreeNode right=lowestCommonAncestor(root.right,A,B);
//Conquer
if(left!=null && right!=null){ //AB位于左右子树两侧
return root;
}
if(left!=null){ //此处右子树应该为空,因为找不到A,B任何一个,AB全在左子树上
return left;
}
if(right!=null){
return right;
}
return null;