Lowest Common Ancestor in a Binary Search Tree
Binary Search Tree
A binary search tree is a type of a binary tree where all the values smaller than any node are present in its left subtree, and all the values greater than it are present at the right subtree.
We are given the root node of the binary search tree and two integer values, n and m. Our task is to return the lowest common ancestor present of both the nodes in the binary search tree.
In the above example, we have a binary search tree, and we will find out the lowest common ancestors of some nodes.
We will find out the root to node1 path and root to node2 path and store it into ArrayList. Now the first common element of the ArrayList will be the lowest common ancestor.
Time complexity: O(H)+O(H), where H is the height of the tree. In the worst case, it can be upto O(N).
Space complexity: O(N)+O(N) in the worst case.
We will use recursion to get the lowest common ancestor of the nodes.
Time complexity: O(N) in the worst case; otherwise, O(H) where H is the height.
Space complexity: O(H) auxiliary recursion space stack.
This approach is the iterative approach of the above solution. It will help us to save the auxiliary stack space occupied by the recursion.
Time complexity: O(H) where H is the height of the tree which can be N in the worst case.
Space complexity: O(1) because no auxiliary space is used.