import java.util.*;
//采用递归方法,二叉树解题的常用方法
/*
* public class TreeNode {
* int val = 0;
* TreeNode left = null;
* TreeNode right = null;
* }
*/
public class Solution {
/**
*
* @param root TreeNode类
* @param o1 int整型
* @param o2 int整型
* @return int整型
*/
public int lowestCommonAncestor (TreeNode root, int o1, int o2) {
// write code here
return leastCommonAncestors(root,o1,o2).val;
}
public TreeNode leastCommonAncestors(TreeNode root, int o1, int o2){
//递归出口,空指针
if(root == null){
return null;
}
//递归出口
if(root.val == o1 || root.val == o2){
return root;
}
//递归左子树
TreeNode left = leastCommonAncestors(root.left,o1,o2);
//递归右子树
TreeNode right = leastCommonAncestors(root.right,o1,o2);
//如果left为空,则说明两个节点在root的右子树上
if(left == null){
return right;
}
//如果right为空,则说明两个节点在root的左子树上
if(right == null){
return left;
}
//如果left,right都不为空,则说明两个节点在root上
return root;
}
}