--- tags: leetcode --- # [235. Lowest Common Ancestor of a Binary Search Tree](https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-search-tree/) --- # My Solution ## The Key Idea for Solving This Coding Question ## C++ Code ```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 != nullptr) { if (p->val < root->val && q->val < root->val) { root = root->left; } else if (root->val < p->val && root->val < q->val) { root = root->right; } else { return root; } } return nullptr; } }; ``` ## Time Complexity $O(H)$ $H$ is the height of the BST referred by `root`. ## Space Complexity $O(1)$ # Miscellane <!-- # Test Cases [6,2,8,0,4,7,9,null,null,3,5] 2 8 ``` ``` [6,2,8,0,4,7,9,null,null,3,5] 2 4 ``` ``` [2,1] 2 1 ``` ``` [6,2,8,0,4,7,9,null,null,3,5] 3 5 ``` -->