Given two Binary Search Trees, find common nodes in them. In other words, find intersection of two BSTs.
Method 1 (Simple Solution) A simple way is to one by once search every node of first tree in second tree. Time complexity of this solution is O(m * h) where m is number of nodes in first tree and h is height of second tree.
Method 2 (Linear Time) We can find common elements in O(n) time.
1) Do inorder traversal of first tree and store the traversal in an auxiliary array ar1. See sortedInorder() here.
2) Do inorder traversal of second tree and store the traversal in an auxiliary array ar2
3) Find intersection of ar1 and ar2. See this for details.
Time complexity of this method is O(m+n) where m and n are number of nodes in first and second tree respectively. This solution requires O(m+n) extra space.
Method 3 (Linear Time and limited Extra Space) We can find common elements in O(n) time and O(h1 + h2) extra space where h1 and h2 are heights of first and second BSTs respectively.
The idea is to use iterative inorder traversal. We use two auxiliary stacks for two BSTs. Since we need to find common elements, whenever we get same element, we print it.
4 7 9 10
This article is contributed by Ekta Goel. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
GeeksforGeeks has prepared a complete interview preparation course with premium videos, theory, practice problems, TA support and many more features. Please refer Placement 100 for details
- Print all odd nodes of Binary Search Tree
- Print all even nodes of Binary Search Tree
- Total number of possible Binary Search Trees and Binary Trees with n keys
- Print common nodes on path from root (or common ancestors)
- Count the Number of Binary Search Trees present in a Binary Tree
- Longest Common Prefix using Binary Search
- Lowest Common Ancestor in a Binary Search Tree.
- Print the path common to the two paths from the root to the two given nodes
- Merge Two Balanced Binary Search Trees
- Self-Balancing-Binary-Search-Trees (Comparisons)
- Check whether the two Binary Search Trees are Identical or Not
- Least Common Ancestor of any number of nodes in Binary Tree
- Pre-Order Successor of all nodes in Binary Search Tree
- Remove all leaf nodes from the binary search tree
- Leaf nodes from Preorder of a Binary Search Tree