Print Common Nodes in Two Binary Search Trees
Last Updated :
23 Jul, 2025
Given two Binary Search Trees, find common nodes in them. In other words, find the intersection of two BSTs.
Example:
Input: root1:
5
/ \
1 10
/ \ /
0 4 7
\
9
root2: 10
/ \
7 20
/ \
4 9
Output: 4 7 9 10
Naive Approach:
A simple way is to one by one search every node of the first tree in the second tree.
Time Complexity: O(M * H) where M is the number of nodes in the first tree and H is the height of the second tree.
Auxiliary Space: O(1)
Common Nodes in Two Binary Search Trees using Inorder and Intersection:
The idea is simply to take the inorder traversal of both the trees and store them in two separate arrays and then find the intersection between two arrays.
Follow the steps below to solve the problem:
- Do inorder traversal of the first tree and store the traversal in an auxiliary array ar1[]. See sortedInorder() here.
- Do inorder traversal of the second tree and store the traversal in an auxiliary array ar2[]
- Find intersection of ar1[] and ar2[].
Below is the implementation of the above approach:
C++
// C++ program of iterative traversal based method to
// find common elements in two BSTs.
#include <iostream>
#include <stack>
#include <vector>
using namespace std;
// A BST node
struct Node {
int key;
struct Node *left, *right;
};
// A utility function to create a new node
Node* newNode(int ele)
{
Node* temp = new Node;
temp->key = ele;
temp->left = temp->right = NULL;
return temp;
}
// A utility function to do inorder traversal
void inorder(struct Node* root, vector<int> &traversal)
{
if (root) {
inorder(root->left, traversal);
traversal.push_back(root->key);
inorder(root->right, traversal);
}
}
// Function two print common elements in given two trees
void printCommon(Node* root1, Node* root2)
{
vector<int> inorder1, inorder2;
// Storing inorder traversal of both the trees
inorder(root1, inorder1);
inorder(root2, inorder2);
cout << "Tree 1 : " << endl;
for(int i = 0; i < inorder1.size(); i++){
cout << inorder1[i] << " ";
}
cout << endl;
cout << "Tree 2 : " << endl;
for(int i = 0; i < inorder2.size(); i++){
cout << inorder2[i] << " ";
}
cout << endl;
cout << "Common Nodes: " << endl;
// Using two pointers calculating common nodes in both the traversals
int i = 0, j = 0;
while(i < inorder1.size() && j < inorder2.size()){
if(inorder1[i] == inorder2[j]){
cout << inorder1[i] << " ";
i++;
j++;
}
else if(inorder1[i] < inorder2[j]){
i++;
}
else{
j++;
}
}
}
// A utility function to insert a new Node
// with given key in BST
struct Node* insert(struct Node* node, int key)
{
// If the tree is empty, return a new Node
if (node == NULL)
return newNode(key);
// Otherwise, recur down the tree
if (key < node->key)
node->left = insert(node->left, key);
else if (key > node->key)
node->right = insert(node->right, key);
// Return the (unchanged) Node pointer
return node;
}
// Driver program
int main()
{
// Create first tree as shown in example
Node* root1 = NULL;
root1 = insert(root1, 5);
root1 = insert(root1, 1);
root1 = insert(root1, 10);
root1 = insert(root1, 0);
root1 = insert(root1, 4);
root1 = insert(root1, 7);
root1 = insert(root1, 9);
// Create second tree as shown in example
Node* root2 = NULL;
root2 = insert(root2, 10);
root2 = insert(root2, 7);
root2 = insert(root2, 20);
root2 = insert(root2, 4);
root2 = insert(root2, 9);
printCommon(root1, root2);
return 0;
}
Java
//Java code for the above approach
import java.util.*;
class Node {
int key;
Node left, right;
public Node(int item)
{
key = item;
left = right = null;
}
}
class BinaryTree {
Node root1, root2;
// A utility function to do inorder traversal
void inorder(Node root, ArrayList<Integer> traversal)
{
if (root != null) {
inorder(root.left, traversal);
traversal.add(root.key);
inorder(root.right, traversal);
}
}
// Function two print common elements in given two trees
void printCommon()
{
ArrayList<Integer> inorder1
= new ArrayList<Integer>();
ArrayList<Integer> inorder2
= new ArrayList<Integer>();
// Storing inorder traversal of both the trees
inorder(root1, inorder1);
inorder(root2, inorder2);
System.out.println("Tree 1 : ");
for (int i = 0; i < inorder1.size(); i++) {
System.out.print(inorder1.get(i) + " ");
}
System.out.println();
System.out.println("Tree 2 : ");
for (int i = 0; i < inorder2.size(); i++) {
System.out.print(inorder2.get(i) + " ");
}
System.out.println();
System.out.println("Common Nodes: ");
// Using two pointers calculating common nodes in
// both the traversals
int i = 0, j = 0;
while (i < inorder1.size() && j < inorder2.size()) {
if (inorder1.get(i) == inorder2.get(j)) {
System.out.print(inorder1.get(i) + " ");
i++;
j++;
}
else if (inorder1.get(i) < inorder2.get(j)) {
i++;
}
else {
j++;
}
}
}
// A utility function to insert a new Node
// with given key in BST
Node insert(Node node, int key)
{
// If the tree is empty, return a new Node
if (node == null) {
return new Node(key);
}
// Otherwise, recur down the tree
if (key < node.key) {
node.left = insert(node.left, key);
}
else if (key > node.key) {
node.right = insert(node.right, key);
}
// Return the (unchanged) Node pointer
return node;
}
public static void main(String[] args)
{
BinaryTree tree = new BinaryTree();
// Create first tree as shown in example
tree.root1 = tree.insert(tree.root1, 5);
tree.root1 = tree.insert(tree.root1, 1);
tree.root1 = tree.insert(tree.root1, 10);
tree.root1 = tree.insert(tree.root1, 0);
tree.root1 = tree.insert(tree.root1, 4);
tree.root1 = tree.insert(tree.root1, 7);
tree.root1 = tree.insert(tree.root1, 9);
// Create second tree as shown in example
tree.root2 = tree.insert(tree.root2, 10);
tree.root2 = tree.insert(tree.root2, 7);
tree.root2 = tree.insert(tree.root2, 20);
tree.root2 = tree.insert(tree.root2, 4);
tree.root2 = tree.insert(tree.root2, 9);
tree.printCommon();
}
}
Python3
# Python program of iterative traversal based method to
# find common elements in two BSTs.
# A BST node
class Node:
def __init__(self):
self.key = 0;
self.left = None
self.right = None
# A utility function to create a new node
def newNode(ele):
temp = Node()
temp.key = ele
temp.left = temp.right = None
return temp
# A utility function to do inorder traversal
def inorder(root, traversal):
if root != None:
inorder(root.left, traversal)
traversal.append(root.key)
inorder(root.right, traversal)
# Function two print common elements in given two trees
def printCommon(root1, root2):
inorder1 = []
inorder2 = []
# Storing inorder traversal of both the trees
inorder(root1, inorder1)
inorder(root2, inorder2)
print("Tree 1 : ")
for i in range(len(inorder1)):
print(inorder1[i], end = " ")
print()
print("Tree 2 : ")
for i in range(len(inorder2)):
print(inorder2[i], end = " ")
print()
print("Common Nodes: ")
# Using two pointers calculating common nodes in both the traversals
i = 0
j = 0
while(i < len(inorder1) and j < len(inorder2)):
if(inorder1[i] == inorder2[j]):
print(inorder1[i], end = " ")
i = i + 1
j = j + 1
elif inorder1[i] < inorder2[j]:
i = i + 1
else:
j = j + 1
print()
# A utility function to insert a new Node
# with given key in BST
def insert(node, key):
# If the tree is empty, return a new Node
if (node == None):
return newNode(key)
# Otherwise, recur down the tree
if (key < node.key):
node.left = insert(node.left, key)
elif key > node.key:
node.right = insert(node.right, key)
# Return the (unchanged) Node pointer
return node
# Driver program
# Create first tree as shown in example
root1 = None
root1 = insert(root1, 5)
root1 = insert(root1, 1)
root1 = insert(root1, 10)
root1 = insert(root1, 0)
root1 = insert(root1, 4)
root1 = insert(root1, 7)
root1 = insert(root1, 9)
# Create second tree as shown in example
root2 = None
root2 = insert(root2, 10)
root2 = insert(root2, 7)
root2 = insert(root2, 20)
root2 = insert(root2, 4)
root2 = insert(root2, 9)
printCommon(root1, root2)
# The code is contributed by Nidhi goel.
C#
using System;
using System.Collections.Generic;
class Node
{
public int key;
public Node left, right;
public Node(int item)
{
key = item;
left = right = null;
}
}
class BinaryTree
{
public Node root1, root2;
// A utility function to do inorder traversal
void Inorder(Node root, List<int> traversal)
{
if (root != null)
{
Inorder(root.left, traversal);
traversal.Add(root.key);
Inorder(root.right, traversal);
}
}
// Function to print common elements in given two trees
public void PrintCommon()
{
List<int> inorder1 = new List<int>();
List<int> inorder2 = new List<int>();
// Storing inorder traversal of both the trees
Inorder(root1, inorder1);
Inorder(root2, inorder2);
Console.WriteLine("Tree 1 : ");
foreach (int p in inorder1)
{
Console.Write(p + " ");
}
Console.WriteLine();
Console.WriteLine("Tree 2 : ");
foreach (int k in inorder2)
{
Console.Write(k+ " ");
}
Console.WriteLine();
Console.WriteLine("Common Nodes: ");
// Using two pointers to calculate common nodes in
// both the traversals
int i = 0, j = 0;
while (i < inorder1.Count && j < inorder2.Count)
{
if (inorder1[i] == inorder2[j])
{
Console.Write(inorder1[i] + " ");
i++;
j++;
}
else if (inorder1[i] < inorder2[j])
{
i++;
}
else
{
j++;
}
}
}
// A utility function to insert a new Node
// with given key in BST
public Node Insert(Node node, int key)
{
// If the tree is empty, return a new Node
if (node == null)
{
return new Node(key);
}
// Otherwise, recur down the tree
if (key < node.key)
{
node.left = Insert(node.left, key);
}
else if (key > node.key)
{
node.right = Insert(node.right, key);
}
// Return the (unchanged) Node pointer
return node;
}
static void Main(string[] args)
{
BinaryTree tree = new BinaryTree();
// Create first tree as shown in example
tree.root1 = tree.Insert(tree.root1, 5);
tree.root1 = tree.Insert(tree.root1, 1);
tree.root1 = tree.Insert(tree.root1, 10);
tree.root1 = tree.Insert(tree.root1, 0);
tree.root1 = tree.Insert(tree.root1, 4);
tree.root1 = tree.Insert(tree.root1, 7);
tree.root1 = tree.Insert(tree.root1, 9);
// Create second tree as shown in example
tree.root2 = tree.Insert(tree.root2, 10);
tree.root2 = tree.Insert(tree.root2, 7);
tree.root2 = tree.Insert(tree.root2, 20);
tree.root2 = tree.Insert(tree.root2, 4);
tree.root2 = tree.Insert(tree.root2, 9);
tree.PrintCommon();
}
}
JavaScript
// javascript program of iterative traversal based method to
// find common elements in two BSTs.
// A BST node
class Node {
constructor(){
this.key = 0;
this.left = null
this.right = null
}
}
// A utility function to create a new node
function newNode(ele)
{
let temp = new Node();
temp.key = ele;
temp.left = temp.right = null;
return temp;
}
// A utility function to do inorder traversal
function inorder(root, traversal)
{
if (root != null) {
inorder(root.left, traversal);
traversal.push(root.key);
inorder(root.right, traversal);
}
}
// Function two print common elements in given two trees
function printCommon(root1, root2)
{
let inorder1 = new Array();
let inorder2 = new Array();
// Storing inorder traversal of both the trees
inorder(root1, inorder1);
inorder(root2, inorder2);
console.log("Tree 1 : \n");
for(let i = 0; i < inorder1.length; i++){
console.log(inorder1[i] + " ");
}
console.log("\n");
console.log("Tree 2 : ");
for(let i = 0; i < inorder2.length; i++){
console.log(inorder2[i] + " ");
}
console.log("\n");
console.log("Common Nodes: \n");
// Using two pointers calculating common nodes in both the traversals
let i = 0, j = 0;
while(i < inorder1.length && j < inorder2.length){
if(inorder1[i] == inorder2[j]){
console.log(inorder1[i] + " ");
i++;
j++;
}
else if(inorder1[i] < inorder2[j]){
i++;
}
else{
j++;
}
}
}
// A utility function to insert a new Node
// with given key in BST
function insert(node, key)
{
// If the tree is empty, return a new Node
if (node == null)
return newNode(key);
// Otherwise, recur down the tree
if (key < node.key)
node.left = insert(node.left, key);
else if (key > node.key)
node.right = insert(node.right, key);
// Return the (unchanged) Node pointer
return node;
}
// Driver program
// Create first tree as shown in example
let root1 = null;
root1 = insert(root1, 5);
root1 = insert(root1, 1);
root1 = insert(root1, 10);
root1 = insert(root1, 0);
root1 = insert(root1, 4);
root1 = insert(root1, 7);
root1 = insert(root1, 9);
// Create second tree as shown in example
let root2 = null;
root2 = insert(root2, 10);
root2 = insert(root2, 7);
root2 = insert(root2, 20);
root2 = insert(root2, 4);
root2 = insert(root2, 9);
printCommon(root1, root2);
// The code is contributed by Nidhi goel.
OutputTree 1 :
0 1 4 5 7 9 10
Tree 2 :
4 7 9 10 20
Common Nodes:
4 7 9 10
Time Complexity: O(M + N), Here 'M' and 'N' are the number of nodes in the first and second trees respectively.
Auxiliary Space: O(M + N), Need two separate arrays for storing inorder traversals of both the trees.
The idea is to use two stacks and store inorder traversal of trees in respective stacks but the maximum number of elements should be equal to that particular branch of the tree.
Follow the steps below to solve the problem:
- Create two stacks for two inorder traversals
- Push the Nodes of the first tree in stack s1, till that branch reaches NULL.
- Push the Nodes of the second tree in stack s2, till that branch reaches NULL
- If both branches reach NULL, then check
- If root1->data < root2->data,
- If node of the first tree is smaller than that of the second tree, then it is obvious that the inorder successors of the current node can have the same value as that of the second tree Node.
- Thus, we pop from s1.
Below is the implementation of the above approach.
C++
// C++ program of iterative traversal based method to
// find common elements in two BSTs.
#include <iostream>
#include <stack>
using namespace std;
// A BST node
struct Node {
int key;
struct Node *left, *right;
};
// A utility function to create a new node
Node* newNode(int ele)
{
Node* temp = new Node;
temp->key = ele;
temp->left = temp->right = NULL;
return temp;
}
// Function two print common elements in given two trees
void printCommon(Node* root1, Node* root2)
{
// Create two stacks for two inorder traversals
stack<Node*> stack1, s1, s2;
while (1) {
// Push the Nodes of first tree in stack s1
if (root1) {
s1.push(root1);
root1 = root1->left;
}
// Push the Nodes of second tree in stack s2
else if (root2) {
s2.push(root2);
root2 = root2->left;
}
// Both root1 and root2 are NULL here
else if (!s1.empty() && !s2.empty()) {
root1 = s1.top();
root2 = s2.top();
// If current keys in two trees are same
if (root1->key == root2->key) {
cout << root1->key << " ";
s1.pop();
s2.pop();
// Move to the inorder successor
root1 = root1->right;
root2 = root2->right;
}
else if (root1->key < root2->key) {
// If Node of first tree is smaller, than
// that of second tree, then its obvious
// that the inorder successors of current
// node can have same value as that of the
// second tree Node. Thus, we pop from s2
s1.pop();
root1 = root1->right;
// root2 is set to NULL, because we need
// new Nodes of tree 1
root2 = NULL;
}
else if (root1->key > root2->key) {
s2.pop();
root2 = root2->right;
root1 = NULL;
}
}
// Both roots and both stacks are empty
else
break;
}
}
// A utility function to do inorder traversal
void inorder(struct Node* root)
{
if (root) {
inorder(root->left);
cout << root->key << " ";
inorder(root->right);
}
}
// A utility function to insert a new Node
// with given key in BST
struct Node* insert(struct Node* node, int key)
{
// If the tree is empty, return a new Node
if (node == NULL)
return newNode(key);
// Otherwise, recur down the tree
if (key < node->key)
node->left = insert(node->left, key);
else if (key > node->key)
node->right = insert(node->right, key);
// Return the (unchanged) Node pointer
return node;
}
// Driver program
int main()
{
// Create first tree as shown in example
Node* root1 = NULL;
root1 = insert(root1, 5);
root1 = insert(root1, 1);
root1 = insert(root1, 10);
root1 = insert(root1, 0);
root1 = insert(root1, 4);
root1 = insert(root1, 7);
root1 = insert(root1, 9);
// Create second tree as shown in example
Node* root2 = NULL;
root2 = insert(root2, 10);
root2 = insert(root2, 7);
root2 = insert(root2, 20);
root2 = insert(root2, 4);
root2 = insert(root2, 9);
cout << "Tree 1 : " << endl;
inorder(root1);
cout << endl;
cout << "Tree 2 : " << endl;
inorder(root2);
cout << "\nCommon Nodes: " << endl;
printCommon(root1, root2);
return 0;
}
Java
// Java program of iterative traversal based method to
// find common elements in two BSTs.
import java.util.*;
class GfG {
// A BST node
static class Node {
int key;
Node left, right;
}
// A utility function to create a new node
static Node newNode(int ele)
{
Node temp = new Node();
temp.key = ele;
temp.left = null;
temp.right = null;
return temp;
}
// Function two print common elements in given two trees
static void printCommon(Node root1, Node root2)
{
Stack<Node> s1 = new Stack<Node>();
Stack<Node> s2 = new Stack<Node>();
while (true) {
// Push the Nodes of first tree in stack s1
if (root1 != null) {
s1.push(root1);
root1 = root1.left;
}
// Push the Nodes of second tree in stack s2
else if (root2 != null) {
s2.push(root2);
root2 = root2.left;
}
// Both root1 and root2 are NULL here
else if (!s1.isEmpty() && !s2.isEmpty()) {
root1 = s1.peek();
root2 = s2.peek();
// If current keys in two trees are same
if (root1.key == root2.key) {
System.out.print(root1.key + " ");
s1.pop();
s2.pop();
// Move to the inorder successor
root1 = root1.right;
root2 = root2.right;
}
else if (root1.key < root2.key) {
// If Node of first tree is smaller,
// than that of second tree, then its
// obvious that the inorder successors
// of current Node can have same value
// as that of the second tree Node.
// Thus, we pop from s2
s1.pop();
root1 = root1.right;
// root2 is set to NULL, because we need
// new Nodes of tree 1
root2 = null;
}
else if (root1.key > root2.key) {
s2.pop();
root2 = root2.right;
root1 = null;
}
}
// Both roots and both stacks are empty
else
break;
}
}
// A utility function to do inorder traversal
static void inorder(Node root)
{
if (root != null) {
inorder(root.left);
System.out.print(root.key + " ");
inorder(root.right);
}
}
// A utility function to insert a new Node
// with given key in BST
static Node insert(Node node, int key)
{
// If the tree is empty, return a new Node
if (node == null)
return newNode(key);
// Otherwise, recur down the tree
if (key < node.key)
node.left = insert(node.left, key);
else if (key > node.key)
node.right = insert(node.right, key);
// Return the (unchanged) Node pointer
return node;
}
// Driver program
public static void main(String[] args)
{
// Create first tree as shown in example
Node root1 = null;
root1 = insert(root1, 5);
root1 = insert(root1, 1);
root1 = insert(root1, 10);
root1 = insert(root1, 0);
root1 = insert(root1, 4);
root1 = insert(root1, 7);
root1 = insert(root1, 9);
// Create second tree as shown in example
Node root2 = null;
root2 = insert(root2, 10);
root2 = insert(root2, 7);
root2 = insert(root2, 20);
root2 = insert(root2, 4);
root2 = insert(root2, 9);
System.out.print("Tree 1 : "
+ "\n");
inorder(root1);
System.out.println();
System.out.print("Tree 2 : "
+ "\n");
inorder(root2);
System.out.println();
System.out.println("Common Nodes: ");
printCommon(root1, root2);
}
}
Python3
# Python3 program of iterative traversal based
# method to find common elements in two BSTs.
# A utility function to create a new node
class newNode:
def __init__(self, key):
self.key = key
self.left = self.right = None
# Function two print common elements
# in given two trees
def printCommon(root1, root2):
# Create two stacks for two inorder
# traversals
s1 = []
s2 = []
while 1:
# append the Nodes of first
# tree in stack s1
if root1:
s1.append(root1)
root1 = root1.left
# append the Nodes of second tree
# in stack s2
elif root2:
s2.append(root2)
root2 = root2.left
# Both root1 and root2 are NULL here
elif len(s1) != 0 and len(s2) != 0:
root1 = s1[-1]
root2 = s2[-1]
# If current keys in two trees are same
if root1.key == root2.key:
print(root1.key, end=" ")
s1.pop(-1)
s2.pop(-1)
# move to the inorder successor
root1 = root1.right
root2 = root2.right
elif root1.key < root2.key:
# If Node of first tree is smaller, than
# that of second tree, then its obvious
# that the inorder successors of current
# Node can have same value as that of the
# second tree Node. Thus, we pop from s2
s1.pop(-1)
root1 = root1.right
# root2 is set to NULL, because we need
# new Nodes of tree 1
root2 = None
elif root1.key > root2.key:
s2.pop(-1)
root2 = root2.right
root1 = None
# Both roots and both stacks are empty
else:
break
# A utility function to do inorder traversal
def inorder(root):
if root:
inorder(root.left)
print(root.key, end=" ")
inorder(root.right)
# A utility function to insert a new Node
# with given key in BST
def insert(node, key):
# If the tree is empty, return a new Node
if node == None:
return newNode(key)
# Otherwise, recur down the tree
if key < node.key:
node.left = insert(node.left, key)
elif key > node.key:
node.right = insert(node.right, key)
# return the (unchanged) Node pointer
return node
# Driver Code
if __name__ == '__main__':
# Create first tree as shown in example
root1 = None
root1 = insert(root1, 5)
root1 = insert(root1, 1)
root1 = insert(root1, 10)
root1 = insert(root1, 0)
root1 = insert(root1, 4)
root1 = insert(root1, 7)
root1 = insert(root1, 9)
# Create second tree as shown in example
root2 = None
root2 = insert(root2, 10)
root2 = insert(root2, 7)
root2 = insert(root2, 20)
root2 = insert(root2, 4)
root2 = insert(root2, 9)
print("Tree 1 : ")
inorder(root1)
print()
print("Tree 2 : ")
inorder(root2)
print()
print("Common Nodes: ")
printCommon(root1, root2)
# This code is contributed by PranchalK
C#
using System;
using System.Collections.Generic;
// C# program of iterative traversal based method to
// find common elements in two BSTs.
public class GfG {
// A BST node
public class Node {
public int key;
public Node left, right;
}
// A utility function to create a new node
public static Node newNode(int ele)
{
Node temp = new Node();
temp.key = ele;
temp.left = null;
temp.right = null;
return temp;
}
// Function two print common elements in given two trees
public static void printCommon(Node root1, Node root2)
{
Stack<Node> s1 = new Stack<Node>();
Stack<Node> s2 = new Stack<Node>();
while (true) {
// push the Nodes of first tree in stack s1
if (root1 != null) {
s1.Push(root1);
root1 = root1.left;
}
// push the Nodes of second tree in stack s2
else if (root2 != null) {
s2.Push(root2);
root2 = root2.left;
}
// Both root1 and root2 are NULL here
else if (s1.Count > 0 && s2.Count > 0) {
root1 = s1.Peek();
root2 = s2.Peek();
// If current keys in two trees are same
if (root1.key == root2.key) {
Console.Write(root1.key + " ");
s1.Pop();
s2.Pop();
// move to the inorder successor
root1 = root1.right;
root2 = root2.right;
}
else if (root1.key < root2.key) {
// If Node of first tree is smaller,
// than that of second tree, then its
// obvious that the inorder successors
// of current Node can have same value
// as that of the second tree Node.
// Thus, we pop from s2
s1.Pop();
root1 = root1.right;
// root2 is set to NULL, because we need
// new Nodes of tree 1
root2 = null;
}
else if (root1.key > root2.key) {
s2.Pop();
root2 = root2.right;
root1 = null;
}
}
// Both roots and both stacks are empty
else {
break;
}
}
}
// A utility function to do inorder traversal
public static void inorder(Node root)
{
if (root != null) {
inorder(root.left);
Console.Write(root.key + " ");
inorder(root.right);
}
}
/* A utility function to insert a new Node with given
* key in BST */
public static Node insert(Node node, int key)
{
/* If the tree is empty, return a new Node */
if (node == null) {
return newNode(key);
}
/* Otherwise, recur down the tree */
if (key < node.key) {
node.left = insert(node.left, key);
}
else if (key > node.key) {
node.right = insert(node.right, key);
}
/* return the (unchanged) Node pointer */
return node;
}
// Driver program
public static void Main(string[] args)
{
// Create first tree as shown in example
Node root1 = null;
root1 = insert(root1, 5);
root1 = insert(root1, 1);
root1 = insert(root1, 10);
root1 = insert(root1, 0);
root1 = insert(root1, 4);
root1 = insert(root1, 7);
root1 = insert(root1, 9);
// Create second tree as shown in example
Node root2 = null;
root2 = insert(root2, 10);
root2 = insert(root2, 7);
root2 = insert(root2, 20);
root2 = insert(root2, 4);
root2 = insert(root2, 9);
Console.Write("Tree 1 : "
+ "\n");
inorder(root1);
Console.WriteLine();
Console.Write("Tree 2 : "
+ "\n");
inorder(root2);
Console.WriteLine();
Console.Write("Common Nodes: "
+ "\n");
printCommon(root1, root2);
}
}
// This code is contributed by Shrikant13
JavaScript
// Javascript equivalent of the python code
// A utility function to create a new node
class Node {
constructor(key) {
this.key = key;
this.left = null;
this.right = null;
}
}
// Function two print common elements in given two trees
function printCommon(root1, root2) {
// Create two stacks for two inorder traversals
let s1 = [], s2 = [];
while (true) {
// append the Nodes of first
// tree in stack s1
if (root1) {
s1.push(root1);
root1 = root1.left;
}
// append the Nodes of second tree
// in stack s2
else if (root2) {
s2.push(root2);
root2 = root2.left;
}
// Both root1 and root2 are NULL here
else if (s1.length !== 0 && s2.length !== 0) {
root1 = s1[s1.length - 1];
root2 = s2[s2.length - 1];
// If current keys in two trees are same
if (root1.key === root2.key) {
console.log(root1.key);
s1.pop();
s2.pop();
// move to the inorder successor
root1 = root1.right;
root2 = root2.right;
}
else if (root1.key < root2.key) {
// If Node of first tree is smaller, than
// that of second tree, then its obvious
// that the inorder successors of current
// Node can have same value as that of the
// second tree Node. Thus, we pop from s2
s1.pop();
root1 = root1.right;
// root2 is set to NULL, because we need
// new Nodes of tree 1
root2 = null;
}
else if (root1.key > root2.key) {
s2.pop();
root2 = root2.right;
root1 = null;
}
}
// Both roots and both stacks are empty
else {
break;
}
}
}
// A utility function to do inorder traversal
function inorder(root) {
if (root) {
inorder(root.left);
console.log(root.key);
inorder(root.right);
}
}
// A utility function to insert a new Node
// with given key in BST
function insert(node, key) {
// If the tree is empty, return a new Node
if (node === null) {
return new Node(key);
}
// Otherwise, recur down the tree
if (key < node.key) {
node.left = insert(node.left, key);
}
else if (key > node.key) {
node.right = insert(node.right, key);
}
// return the (unchanged) Node pointer
return node;
}
// Driver Code
let root1 = null;
root1 = insert(root1, 5);
root1 = insert(root1, 1);
root1 = insert(root1, 10);
root1 = insert(root1, 0);
root1 = insert(root1, 4);
root1 = insert(root1, 7);
root1 = insert(root1, 9);
// Create second tree as shown in example
let root2 = null;
root2 = insert(root2, 10);
root2 = insert(root2, 7);
root2 = insert(root2, 20);
root2 = insert(root2, 4);
root2 = insert(root2, 9);
console.log("Tree 1 : ");
inorder(root1);
console.log();
console.log("Tree 2 : ");
inorder(root2);
console.log();
console.log("Common Nodes: ");
printCommon(root1, root2);
OutputTree 1 :
0 1 4 5 7 9 10
Tree 2 :
4 7 9 10 20
Common Nodes:
4 7 9 10
Time Complexity: O(N+M). Here 'M' and 'N' are the number of nodes in the first and second trees respectively
Auxiliary Space: O(h1 + h2), Where h1 and h2 are the heights of the first and second tree respectively.
Find Common Nodes in two BSTs | DSA Problem
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem