/**
* 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) {
TreeNode tmp = root;
TreeNode res = null;
int small = 0, big = 0;
if(p.val > q.val){
small = q.val;
}else{
small = p.val;
}
big = p.val + q.val - small;
if(tmp.val >= small && tmp.val <= big){
res = tmp;
}else{
if(tmp.val > big){
res = lowestCommonAncestor(tmp.left, p, q);
}else if(tmp.val < small){
res = lowestCommonAncestor(tmp.right, p, q);
}
}
return res;
}
}
* 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) {
TreeNode tmp = root;
TreeNode res = null;
int small = 0, big = 0;
if(p.val > q.val){
small = q.val;
}else{
small = p.val;
}
big = p.val + q.val - small;
if(tmp.val >= small && tmp.val <= big){
res = tmp;
}else{
if(tmp.val > big){
res = lowestCommonAncestor(tmp.left, p, q);
}else if(tmp.val < small){
res = lowestCommonAncestor(tmp.right, p, q);
}
}
return res;
}
}