My version:1
2
3
4
5
6public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
if ((root.val - p.val) * (root.val - q.val) < 0) return root;
if (root.val > Math.max(p.val, q.val)) return lowestCommonAncestor(root.left, p, q);
else if (root.val < Math.min(p.val, q.val)) return lowestCommonAncestor(root.right, p, q);
return root;
}
previous 2019 version:1
2
3
4
5
6
7
8TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
if (!root) return NULL;
if (root->val > max(p->val, q->val))
return lowestCommonAncestor(root->left, p, q);
else if (root->val < min(p->val, q->val))
return lowestCommonAncestor(root->right, p, q);
else return root;
}