题目:Given a binary search tree (BST), find the lowest common ancestor (LCA) of two given nodes in the BST.
思路:
两节点 p , q , 分多中情况考虑, 因为是BST, 如果 p < root , q > root ==> LCA = root
如果 p = Max(p , q ) < root == 》 LCA = LCA (root.left , p ,q) // 在左子树中求LCA
p = Max(p , q ) > root 同理
public class Solution {
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
int min = Math.min(p.val , q.val);
int max = Math.max(p.val , q.val);
while(root != null) {
if(root.val > max) {
return lowestCommonAncestor(root.left , p , q);
} else if(root.val < max){
if(root.val >= min)
return root;
return lowestCommonAncestor(root.right, p , q);
} else if(root.val == max)
return root;
}
return null;
}
}