14. Find Common Nodes in two BSTs
Last updated
Last updated
The problem can be found at the following link: Question Link
I have implemented a solution that involves an in-order traversal of the first BST (root1) and for each visited node, I check if that node's data exists in the second BST (root2) by performing a search operation. If it exists in the second BST, I add it to the out
vector.
Here are the steps:
Initialize an empty vector out
to store the common nodes.
Perform an in-order traversal of the first BST (root1) and, for each visited node:
Check if that node's value exists in the second BST (root2) by calling the find
function.
If the value is found in the second BST, add it to the out
vector.
Return the out
vector containing the common nodes.
Time Complexity: The time complexity of this solution is O(N1.log(N2))
, where N1
and N2
are the number of nodes in root1
and root2
respectively. This is because we visit each node in both trees once during the inorder
traversal.
Auxiliary Space Complexity: The auxiliary space complexity is O(H1 + H2)
, where H1
and H2
is the height of both trees in the recursion stack.
For discussions, questions, or doubts related to this solution, please visit our discussion section. We welcome your input and aim to foster a collaborative learning environment.
If you find this solution helpful, consider supporting us by giving a ⭐ star to the getlost01/gfg-potd repository.