14. Find Common Nodes in two BSTs
The problem can be found at the following link: Question Link
My Approach
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 and Auxiliary Space Complexity
Time Complexity: The time complexity of this solution is
O(N1.log(N2))
, whereN1
andN2
are the number of nodes inroot1
androot2
respectively. This is because we visit each node in both trees once during theinorder
traversal.Auxiliary Space Complexity: The auxiliary space complexity is
O(H1 + H2)
, whereH1
andH2
is the height of both trees in the recursion stack.
Code (C++)
Contribution and Support
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.
Last updated