> For the complete documentation index, see [llms.txt](https://jenhsuan.gitbook.io/algorithm/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://jenhsuan.gitbook.io/algorithm/leetcode/235.-lowest-common-ancestor-of-a-binary-search-tree.md).

# 235. Lowest Common Ancestor of a Binary Search Tree

## 1.問題

* 給一個BST, 找出兩個node的LCA

![](/files/-LJ9Rj3X9f3bY0FPCDYO)

## 2.想法

* 提問
  * 確認題意:  是否是BST?&#x20;
* function header, parameter
* test input
* 說明想法
  * 利用BST特性
    * 當root比兩個node都大時, 將root移動到左邊
    * 當root比兩個node都小時, 將root移動到右邊
    * 當root介於兩個node間時, 將root停止移動
* 測試計算複雜度

## 3.程式碼

```
/**
 * 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) {
        if (!root) {
            return NULL;
        }
        
        if (root->val > p->val && root->val > q->val) {
            return lowestCommonAncestor(root->left, p, q);
        } else if (root->val < p->val && root->val < q->val) {
            return lowestCommonAncestor(root->right, p, q);
        } else {
            return root;
        }
    }
};
```
