The idea is simple. We just need to find the latest common node of their search path in the bst tree.

```
struct TreeNode* lowestCommonAncestor(struct TreeNode* root, struct TreeNode* p, struct TreeNode* q)
{
struct TreeNode *result = root;
int v1 = p->val, v2 = q->val;
p = q = root;
while (p && q) {
if (p == q) result = p; else break;
if (p->val > v1) p = p->left; else if (p->val < v1) p = p->right; else break;
if (q->val > v2) q = q->left; else if (q->val < v2) q = q->right; else break;
}
return result;
}
```