In this video, we explore how to find the Lowest Common Ancestor (LCA) in a Binary Search Tree (BST). The LCA of two nodes is the lowest node that has both nodes as descendants, with the added condition that the node itself can be a descendant of itself. We present two approaches: the recursive method and the iterative method. In the recursive approach, we check if both nodes are smaller or greater than the current node, recursively traversing left or right subtrees until the LCA is found. If one node is smaller and the other is larger, the current node is the LCA.
The iterative method improves upon the recursive approach by eliminating the need for recursion, optimizing space complexity to O(1). We traverse the BST iteratively, checking the values of n1 and n2 at each node. If both n1 and n2 are smaller than the current node, we move left; if both are greater, we move right. Once we find a node where one value is smaller and the other is larger, that node is the LCA. This method maintains the efficiency of the recursive approach while using constant space.
For more details, lease go through -LCA in BST – Lowest Common Ancestor in Binary Search Tree