# Leetcode [No. 235] Lowest Common Ancestor of a Binary Search Tree(MEDIUM) ## 題目 https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-search-tree/description/ ## 思路 + 這個解法運用了BinarySearchTree的特性 ```c++ /** * 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) { TreeNode* cur = root; int biggerVal = max(p->val, q->val); int smallerVal = min(p->val, q->val); while(cur!=nullptr) { if(cur->val > biggerVal) { cur = cur->left; // this } else if (cur->val < smallerVal) { cur = cur->right; } else // in the corrent bound { return cur; } } return nullptr; } }; ``` ### 解法分析 + time complexity: O(lgn) ### 執行結果 ![image](https://hackmd.io/_uploads/BJy2PUnU6.png)