# 235. Lowest Common Ancestor of a Binary Search Tree

{% embed url="<https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-search-tree/description/>" %}

### 2nd try

> time: O(n)

> space: O(h), worst O(n)

```jsx
var lowestCommonAncestor = function(root, p, q) {
    if (root === null) return root;

    if (p.val < root.val && q.val < root.val) {
        return lowestCommonAncestor(root.left, p, q);
    } else if (root.val < p.val && root.val < q.val) {
        return lowestCommonAncestor(root.right, p, q);
    }
    
    return root;
};
```

###

### 1st try

> time: O(n)

> Space: O(n)

```jsx
/**
 * 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 (containsB(p, q)) return p;
    if (containsB(q, p)) return q;

    const ids = [];
    ids[root.val] = root;

    const queue = [[root, root]];

    while (queue.length > 0) {
        const [node, parentNode] = queue.shift();
        if (node === null) continue;

        ids[node.val] = parentNode;
        queue.push([node.left, node]);
        queue.push([node.right, node]);
    }

    let current = p;
    const pPath = [p];
    while (ids[current.val] !== current) {
        pPath.unshift(ids[current.val]);
        current = ids[current.val];
    }

    current = q;
    const qPath = [q];
    while (ids[current.val] !== current) {
        qPath.unshift(ids[current.val]);
        current = ids[current.val];
    }

    let idx = 1;
    while (pPath[idx] === qPath[idx]) {
        idx++;
    }

    return pPath[idx - 1];
}

function containsB(node, b) {
    if (node === null) return false;

    if (node === b) {
        return true;
    }

    const left = containsB(node.left, b);
    const right = containsB(node.right, b);

    return left || right;
}
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://algorithm.prettylog.com/top-75-leetcode-questions-to-save-your-time/problems/tree/235.-lowest-common-ancestor-of-a-binary-search-tree.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
