思路:
针对BST的特点,通过看给定的2个节点的位置与root位置的关系来搜索。
如果在root的一左一右,那么root就是该BST的LCA;
如果都在root的左面,那么递归的搜索root的左子树;
如果都在root的右面,那么递归的搜索root的右子树;
java code :
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
if(root == null) return null;
int min, max;
if(p.val > q.val) {
min = q.val;
max = p.val;
}else {
min = p.val;
max = q.val;
}
if(root.val > max) {
return lowestCommonAncestor(root.left, p, q);
}
if(root.val < min) {
return lowestCommonAncestor(root.right, p, q);
}
return root;
}
}