![](https://img-blog.csdnimg.cn/3279be13b5e14f43b3d2cbdc9bd1d5cf.png)
解题思路1:
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
if(root == null){
return -1;
}
if(o1 == root.val || o2 == root.val){
return root.val;
}
int left = lowestCommonAncestor(root.left, o1, o2);
int right = lowestCommonAncestor(root.right, o1, o2);
if(left == -1){
return right;
}
if(right == -1){
return left;
}
return root.val;
}
}
解题思路2:
import java.util.*;
/*
* public class TreeNode {
* int val = 0;
* TreeNode left = null;
* TreeNode right = null;
* public TreeNode(int val) {
* this.val = val;
* }
* }
*/
public class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param root TreeNode类
* @param p int整型
* @param q int整型
* @return int整型
*/
public int lowestCommonAncestor (TreeNode root, int p, int q) {
// write code here
int min = Math.min(p, q);
int max = Math.max(p, q);
//当root.val大于min,同时大于max,则公共祖先节点在左子树
if (root.val > min && root.val > max)
return lowestCommonAncestor(root.left, p, q);
//当root.val大于min,同时大于max,则公共祖先节点在右子树
if (root.val < min && root.val < max)
return lowestCommonAncestor(root.right, p, q);
/**
只剩下两种情况:
1.当root.val等于min或者max,则为root.val
if (root.val == min || root.val == max)
return root.val;
2.当root.val小于左边大于右边,则为root.val
if (root.val > min && root.val < max)
return root.val;
*/
return root.val;
}
}