BiruLyu
5/30/2017 - 6:53 PM

## 235. Lowest Common Ancestor of a Binary Search Tree(1st).java

``````/**
* 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 || p == null || q == null) return null;

//if((root.val >= q.val && root.val <= p.val) || (root.val >= p.val && root.val <= q.val)) {
//return root;

while((root.val - (long)p.val) * (root.val - (long)q.val) > 0) {// in case of overflow
root = p.val < root.val ? root.left : root.right;
}
return root;

}
}``````
``````public class Solution {
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
if (root == null || p == null || q == null) return root;

if (root.val > p.val && root.val > q.val) return lowestCommonAncestor(root.left, p, q);
if (root.val < p.val && root.val < q.val) return lowestCommonAncestor(root.right, p, q);

return root;

}
}``````