Appearance
Approach: BST walk: go left if both targets are smaller, right if both larger, otherwise current is LCA.
Complexity: O(h) time, O(h) space
js
/**
* Definition for a binary tree node.
* function TreeNode(val) {
* this.val = val;
* this.left = this.right = null;
* }
*/
/**
* @param {TreeNode} root
* @param {TreeNode} p
* @param {TreeNode} q
* @return {TreeNode}
*/
var lowestCommonAncestor = function(root, p, q) {
if (!root) {
return null
}
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
};