# 235. Lowest Common Ancestor of a Binary Search Tree

Given a binary search tree (BST), find the lowest common ancestor (LCA) of two given nodes in the BST.

According to the[definition of LCA on Wikipedia](https://en.wikipedia.org/wiki/Lowest_common_ancestor): “The lowest common ancestor is defined between two nodes v and w as the lowest node in T that has both v and w as descendants (where we allow**a node to be a descendant of itself**).”

```
        _______6______
       /              \
    ___2__          ___8__
   /      \        /      \
   0      _4       7       9
         /  \
         3   5
```

For example, the lowest common ancestor (LCA) of nodes`2`and`8`is`6`. Another example is LCA of nodes`2`and`4`is`2`, since a node can be a descendant of itself according to the LCA definition.

**Thoughts:**

Because of BST, we can decide which branch to to based on values. Two ways to approach this problem:

1. **Iterative, O(1) space : Iteratively traversing down the side on which two nodes reside until the "split" is found.**
2. **Recuesive**

**Iterative:**

**Code 1**&#x20;

```cpp
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
        while((root->val - p->val) * (root-> val - q->val) > 0) 
            root = (root-> val) > (p->val)? (root->left): (root-> right);
            // =0 means either the current node is a. root is one of {p,q} b. root is the lowest parent of p and q.
        return root;
    }
};
```

**Code 1 (Java)**

```java
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
    while ((root.val - p.val) * (root.val - q.val) > 0)
        root = p.val < root.val ? root.left : root.right;
    return root;
}
```

**Code 1 (Python)**

```python
def lowestCommonAncestor(self, root, p, q):
    while (root.val - p.val) * (root.val - q.val) > 0:
        root = (root.left, root.right)[p.val > root.val]
    return root
```

```python
def lowestCommonAncestor(self, root, p, q):
    while root:
        if p.val < root.val > q.val:
            root = root.left
        elif p.val > root.val < q.val:
            root = root.right
        else:
            return root
```

**Recursive**

**Code 2**&#x20;

```cpp
class Solution {
public:
    TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
        return (root-> val - p-> val)*(root ->val - q->val) > 0 ?
            lowestCommonAncestor(p->val < root->val ? root->left: root->right, p , q): root;
    }
};
```

**Code 2 (Java)**

```java
class Solution {
    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        return (root.val - p.val) * (root.val - q.val) > 0 ? 
            lowestCommonAncestor(p.val - root.val < 0 ? root.left: root.right, p , q) : root;
    }
}
```

**Code 2 (Python)**

```python
class Solution(object):
    def lowestCommonAncestor(self, root, p, q):
        return self.lowestCommonAncestor((root.left, root.right)[p.val > root.val], p, q) \
                if (root.val - p.val) * (root.val - q.val) > 0  else root
```

Special thanks to [StefanPochmann](https://discuss.leetcode.com/user/stefanpochmann) as he nailed this problem again over [here](https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-search-tree/discuss/).


---

# 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://code.taozirui.com/lc/tree-traversal/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.
