/**
* 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;
}
}