一:题目
二:上码
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
if (root == q || root == p || root == null) return root;
if (root.val > p.val && root.val > q.val) {//p,q存在于左子树中
TreeNode left_node = lowestCommonAncestor(root.left,p,q);
return left_node;
} else if (root.val < p.val && root.val <q.val) {//p,q存在于右子树中
TreeNode right_node = lowestCommonAncestor(root.right,p,q);
return right_node;//返回最先找到的
} else
return root;
}
}