I.递归法
根据二叉搜索树的性质,判断两个节点p,q 是否在root 的同一侧,如果在的话说明p,q的相同父节点是root 的子节点;如果判断p,q 在root 的异侧那么就返回根节点root.
/**
* 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(p.val>root.val&&q.val>root.val) return lowestCommonAncestor(root.right,p,q);
else if(p.val<root.val&&q.val<root.val) return lowestCommonAncestor(root.left,p,q);
else return root;
}
}
II. 递归
四种情况
①p,q 节点之一在、等于root 的节点
②p,q节点 都在root 的左子树
③p,q节点都在root 的右子树
④p,q节点在root 的两侧
/**
* 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==null) return null;
if(p==root||q==root) return root;
TreeNode left=lowestCommonAncestor(root.left,p,q);
TreeNode right=lowestCommonAncestor(root.right,p,q);
if(left==null) return right;
if(right==null) return left;
return root;
}
}