Finding the Lowest Common Ancestor (LCA) of a Binary Search Tree (BST) is a relatively simple structure compared to other Binary Tree structures. In this article, we will discuss a solution to find the Lowest Common Ancestor of a Binary Search Tree using an iterative approach.

## Overview

In a Binary Search Tree, the Lowest Common Ancestor of two given nodes is the node that lies on the path between the two given nodes, with the lowest depth. Therefore, to find the Lowest Common Ancestor of two nodes, we need to find the paths from the root to each of the two given nodes. After finding the paths, we can compare the paths and find the common ancestor that has the lowest depth.

## Algorithm

We can follow the steps below to find the Lowest Common Ancestor of two given nodes in a Binary Search Tree.

- First, we will store the root node of the given Binary Search Tree in a Stack.
- Then, we will find the path from the root to each of the two given nodes in the BST.
- After finding the paths, we can compare the two paths and find the common ancestor with the lowest depth.

## Pseudocode

```
function lowestCommonAncestor(root, node1, node2)
result = null
stack = [root]
while (stack is not empty)
node = stack.pop()
if (node is equal to node1 or node2):
result = node
if (node is not leaf node):
add all of node’s children to stack
return result
```

## Time Complexity

The time complexity of this algorithm is `O(N)`

, where `N`

is the number of nodes in the BST.

## Space Complexity

The space complexity of this algorithm is `O(N)`

, where `N`

is the number of nodes in the BST.

## FAQ

##### What is the Lowest Common Ancestor of a Binary Search Tree?

The Lowest Common Ancestor (LCA) of a Binary Search Tree (BST) is the node that lies on the path between two given nodes, with the lowest depth.

##### How can I find the Lowest Common Ancestor of two nodes in a Binary Search Tree?

To find the Lowest Common Ancestor (LCA) of two nodes in a Binary Search Tree, you can find the paths from the root to each of the two given nodes and then compare the paths and find the common ancestor with the lowest depth.

##### What is the time complexity of this algorithm?

The time complexity of this algorithm is `O(N)`

, where `N`

is the number of nodes in the BST.

##### What is the space complexity of this algorithm?

The space complexity of this algorithm is `O(N)`

, where `N`

is the number of nodes in the BST.

##### Are there any other solutions to find the Lowest Common Ancestor of two nodes?

Yes, there are other solutions to find the Lowest Common Ancestor of two nodes. For example, you can use a recursive approach or a divide-and-conquer approach. You can read more about this here.