/**
* Definition of TreeNode:
* public class TreeNode {
* public int val;
* public TreeNode left, right;
* public TreeNode(int val) {
* this.val = val;
* this.left = this.right = null;
* }
* }
*/
/*
递归实现 1: 出口是走到底端;
2: 步骤是往左右两边传递;
3: 分情况讨论:(1)如果root== A或者B;那么return root;
(2)如果左子树和右子树都找到了值,return root;
(3)如果左右有一个为空 return 另一个;
*/
public class Solution {
/*
* @param root: The root of the binary search tree.
* @param A: A TreeNode in a Binary.
* @param B: A TreeNode in a Binary.
* @return: Return the least common ancestor(LCA) of the two nodes.
*/
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode A, TreeNode B) {
// write your code here
if(root == null) return root;
TreeNode left = lowestCommonAncestor(root.left, A, B);
TreeNode right = lowestCommonAncestor(root.right, A, B);
if(root == A || root == B) return root;
if(left != null && right != null) return root;
if(left == null) return right;
if(right == null) return left;
return null;
}
}