> For the complete documentation index, see [llms.txt](https://shangan.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://shangan.gitbook.io/algorithm/he-xin-suan-fa-200-ti/untitled-2/lowest-common-ancestor-of-a-binary-search-tree.md).

# Lowest Common Ancestor of a Binary Search Tree

{% tabs %}
{% tab title="Java" %}

```java
class Solution {
	public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
			if (root == null) return null;
			int keyVal = root.val;
			int pVal = p.val;
			int qVal = q.val;
		
	if (keyVal > pVal && keyVal > qVal) {
			return lowestCommonAncestor(root.left, p, q);
		} else if (keyVal < pVal && keyVal < qVal) {
			return lowestCommonAncestor(root.right, p, q);
		} else {
			return root;
		}
	}
}
```

{% endtab %}
{% endtabs %}
