Lowest Common Ancestor in a Binary Search TreeBinary Search TreeA 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. Problem statementWe 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. For example: In the above example, we have a binary search tree, and we will find out the lowest common ancestors of some nodes.
Approach 1We 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. Java code: Output: 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. Method 2We will use recursion to get the lowest common ancestor of the nodes.
Java code: Output: Time complexity: O(N) in the worst case; otherwise, O(H) where H is the height. Space complexity: O(H) auxiliary recursion space stack. Method 3This approach is the iterative approach of the above solution. It will help us to save the auxiliary stack space occupied by the recursion. Java code: Output: 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.
Next TopicTypes of Hash Functions in C
