Print Common Nodes in Two Binary Search Trees

Last Updated : 31 Jul, 2026

Given the roots r1 and r2 of two Binary Search Trees (BSTs), find all node values that are present in both trees. Return the common node values in sorted order.

Example: 

Input: r1 = [5, 1, 10, 0, 4, 7, N, N, N, N, N, N, 9], r2 = [10, 7, 20, 4, 9, N, N]

2056958520

Output: [4, 7, 9, 10]
Explanation: The nodes 4, 7, 9, and 10 are present in both BSTs.

Input: r1 = [10, 2, 11, 1, 3, N, N], r2 = [2, 1, 3]

2056958519

Output: [1, 2, 3]  
Explanation: The nodes 1, 2, and 3 are present in both BSTs. Hence, the common nodes in sorted order are [1, 2, 3].              

Try It Yourself
redirect icon

[Naive Approach] Using Inorder Traversal with BST Search - O(n × h) Time and O(h) Space

The idea is to traverse the first BST in inorder so that the nodes are visited in sorted order. For every node encountered, search for the same value in the second BST using the BST search operation.

If the value is found in the second BST, add it to the result. Since the first BST is traversed in inorder, the common nodes are automatically collected in sorted order.

C++
#include <iostream>
#include <vector>
using namespace std;

// Structure of a BST node.
class Node
{
  public:
    int data;
    Node *left;
    Node *right;

    Node(int val)
    {
        data = val;
        left = right = nullptr;
    }
};

// Insert a node into the BST.
Node *insert(Node *root, int key)
{
    if (!root)
        return new Node(key);

    if (key < root->data)
        root->left = insert(root->left, key);
    else
        root->right = insert(root->right, key);

    return root;
}

// Search for a key in the BST.
bool search(Node *root, int key)
{
    if (!root)
        return false;

    if (root->data == key)
        return true;

    if (key < root->data)
        return search(root->left, key);

    return search(root->right, key);
}

// Traverse the first BST in inorder.
void inorder(Node *root, Node *r2, vector<int> &res)
{
    if (!root)
        return;

    inorder(root->left, r2, res);

    if (search(r2, root->data))
        res.push_back(root->data);

    inorder(root->right, r2, res);
}

// Function to return the common nodes of two BSTs.
vector<int> findCommon(Node *r1, Node *r2)
{
    vector<int> res;

    inorder(r1, r2, res);

    return res;
}

int main()
{

    // First BST
    //
    //          5
    //        /   \
    //       1     10
    //      / \    /
    //     0   4  7
    //            \
    //             9
    //
    Node *r1 = nullptr;
    r1 = insert(r1, 5);
    r1 = insert(r1, 1);
    r1 = insert(r1, 10);
    r1 = insert(r1, 0);
    r1 = insert(r1, 4);
    r1 = insert(r1, 7);
    r1 = insert(r1, 9);

    // Second BST
    //
    //        10
    //       /  \
    //      7    20
    //     / \
    //    4   9
    //
    Node *r2 = nullptr;
    r2 = insert(r2, 10);
    r2 = insert(r2, 7);
    r2 = insert(r2, 20);
    r2 = insert(r2, 4);
    r2 = insert(r2, 9);

    vector<int> res = findCommon(r1, r2);

    // Print the array.
    cout << "[";
    for (int i = 0; i < res.size(); i++)
    {
        cout << res[i];
        if (i != res.size() - 1)
            cout << ", ";
    }
    cout << "]";

    return 0;
}
Java
import java.util.*;

// Structure of a BST node.
class Node {
    int data;
    Node left;
    Node right;

    Node(int val) {
        data = val;
        left = right = null;
    }
}

public class GFG {

    // Insert a node into the BST.
    static Node insert(Node root, int key) {
        if (root == null)
            return new Node(key);

        if (key < root.data)
            root.left = insert(root.left, key);
        else
            root.right = insert(root.right, key);

        return root;
    }

    // Search for a key in the BST.
    static boolean search(Node root, int key) {
        if (root == null)
            return false;

        if (root.data == key)
            return true;

        if (key < root.data)
            return search(root.left, key);

        return search(root.right, key);
    }

    // Traverse the first BST in inorder.
    static void inorder(Node root, Node r2, ArrayList<Integer> res) {
        if (root == null)
            return;

        inorder(root.left, r2, res);

        if (search(r2, root.data))
            res.add(root.data);

        inorder(root.right, r2, res);
    }

    // Function to return the common nodes of two BSTs.
    static ArrayList<Integer> findCommon(Node r1, Node r2) {
        ArrayList<Integer> res = new ArrayList<>();

        inorder(r1, r2, res);

        return res;
    }

    public static void main(String[] args) {

        // First BST
        //
        //          5
        //        /   \
        //       1     10
        //      / \    /
        //     0   4  7
        //            \
        //             9
        //
        Node r1 = null;
        r1 = insert(r1, 5);
        r1 = insert(r1, 1);
        r1 = insert(r1, 10);
        r1 = insert(r1, 0);
        r1 = insert(r1, 4);
        r1 = insert(r1, 7);
        r1 = insert(r1, 9);

        // Second BST
        //
        //        10
        //       /  \
        //      7    20
        //     / \
        //    4   9
        //
        Node r2 = null;
        r2 = insert(r2, 10);
        r2 = insert(r2, 7);
        r2 = insert(r2, 20);
        r2 = insert(r2, 4);
        r2 = insert(r2, 9);

        ArrayList<Integer> res = findCommon(r1, r2);

        // Print the array.
        System.out.print("[");
        for (int i = 0; i < res.size(); i++) {
            System.out.print(res.get(i));
            if (i != res.size() - 1)
                System.out.print(", ");
        }
        System.out.print("]");
    }
}
Python
# Structure of a BST node.
class Node:
    def __init__(self, val):
        self.data = val
        self.left = None
        self.right = None


# Insert a node into the BST.
def insert(root: 'Node', key: int) -> 'Node':
    if not root:
        return Node(key)

    if key < root.data:
        root.left = insert(root.left, key)
    else:
        root.right = insert(root.right, key)

    return root


# Search for a key in the BST.
def search(root: 'Node', key: int) -> bool:
    if not root:
        return False

    if root.data == key:
        return True

    if key < root.data:
        return search(root.left, key)

    return search(root.right, key)


# Traverse the first BST in inorder.
def inorder(root: 'Node', r2: 'Node', res: list[int]) -> None:
    if not root:
        return

    inorder(root.left, r2, res)

    if search(r2, root.data):
        res.append(root.data)

    inorder(root.right, r2, res)


# Function to return the common nodes of two BSTs.
def findCommon(r1: 'Node', r2: 'Node') -> list[int]:
    res = []

    inorder(r1, r2, res)

    return res


def main():

    # First BST
    #
    #          5
    #        /   \
    #       1     10
    #      / \    /
    #     0   4  7
    #            \
    #             9
    #
    r1 = None
    r1 = insert(r1, 5)
    r1 = insert(r1, 1)
    r1 = insert(r1, 10)
    r1 = insert(r1, 0)
    r1 = insert(r1, 4)
    r1 = insert(r1, 7)
    r1 = insert(r1, 9)

    # Second BST
    #
    #        10
    #       /  \
    #      7    20
    #     / \
    #    4   9
    #
    r2 = None
    r2 = insert(r2, 10)
    r2 = insert(r2, 7)
    r2 = insert(r2, 20)
    r2 = insert(r2, 4)
    r2 = insert(r2, 9)

    res = findCommon(r1, r2)

    # Print the array.
    print("[", end="")
    for i in range(len(res)):
        print(res[i], end="")
        if i != len(res) - 1:
            print(", ", end="")
    print("]")


if __name__ == "__main__":
    main()
C#
using System;
using System.Collections.Generic;

// Structure of a BST node.
class Node
{
    public int data;
    public Node left;
    public Node right;

    public Node(int val)
    {
        data = val;
        left = right = null;
    }
}

class GFG
{
    // Insert a node into the BST.
    static Node insert(Node root, int key)
    {
        if (root == null)
            return new Node(key);

        if (key < root.data)
            root.left = insert(root.left, key);
        else
            root.right = insert(root.right, key);

        return root;
    }

    // Search for a key in the BST.
    static bool search(Node root, int key)
    {
        if (root == null)
            return false;

        if (root.data == key)
            return true;

        if (key < root.data)
            return search(root.left, key);

        return search(root.right, key);
    }

    // Traverse the first BST in inorder.
    static void inorder(Node root, Node r2, List<int> res)
    {
        if (root == null)
            return;

        inorder(root.left, r2, res);

        if (search(r2, root.data))
            res.Add(root.data);

        inorder(root.right, r2, res);
    }

    // Function to return the common nodes of two BSTs.
    static List<int> findCommon(Node r1, Node r2)
    {
        List<int> res = new List<int>();

        inorder(r1, r2, res);

        return res;
    }

    static void Main()
    {
        // First BST
        //
        //          5
        //        /   \
        //       1     10
        //      / \    /
        //     0   4  7
        //            \
        //             9
        //
        Node r1 = null;
        r1 = insert(r1, 5);
        r1 = insert(r1, 1);
        r1 = insert(r1, 10);
        r1 = insert(r1, 0);
        r1 = insert(r1, 4);
        r1 = insert(r1, 7);
        r1 = insert(r1, 9);

        // Second BST
        //
        //        10
        //       /  \
        //      7    20
        //     / \
        //    4   9
        //
        Node r2 = null;
        r2 = insert(r2, 10);
        r2 = insert(r2, 7);
        r2 = insert(r2, 20);
        r2 = insert(r2, 4);
        r2 = insert(r2, 9);

        List<int> res = findCommon(r1, r2);

        // Print the array.
        Console.Write("[");
        for (int i = 0; i < res.Count; i++)
        {
            Console.Write(res[i]);
            if (i != res.Count - 1)
                Console.Write(", ");
        }
        Console.Write("]");
    }
}
JavaScript
// Structure of a BST node.
class Node {
    constructor(val) {
        this.data = val;
        this.left = null;
        this.right = null;
    }
}

// Insert a node into the BST.
function insert(root, key) {
    if (!root)
        return new Node(key);

    if (key < root.data)
        root.left = insert(root.left, key);
    else
        root.right = insert(root.right, key);

    return root;
}

// Search for a key in the BST.
function search(root, key) {
    if (!root)
        return false;

    if (root.data === key)
        return true;

    if (key < root.data)
        return search(root.left, key);

    return search(root.right, key);
}

// Traverse the first BST in inorder.
function inorder(root, r2, res) {
    if (!root)
        return;

    inorder(root.left, r2, res);

    if (search(r2, root.data))
        res.push(root.data);

    inorder(root.right, r2, res);
}

// Function to return the common nodes of two BSTs.
function findCommon(r1, r2) {
    let res = [];

    inorder(r1, r2, res);

    return res;
}

// Driver code

    // First BST
    //
    //          5
    //        /   \
    //       1     10
    //      / \    /
    //     0   4  7
    //            \
    //             9
    //
    let r1 = null;
    r1 = insert(r1, 5);
    r1 = insert(r1, 1);
    r1 = insert(r1, 10);
    r1 = insert(r1, 0);
    r1 = insert(r1, 4);
    r1 = insert(r1, 7);
    r1 = insert(r1, 9);

    // Second BST
    //
    //        10
    //       /  \
    //      7    20
    //     / \
    //    4   9
    //
    let r2 = null;
    r2 = insert(r2, 10);
    r2 = insert(r2, 7);
    r2 = insert(r2, 20);
    r2 = insert(r2, 4);
    r2 = insert(r2, 9);

    let res = findCommon(r1, r2);

    // Print the array.
    process.stdout.write("[");
    for (let i = 0; i < res.length; i++) {
        process.stdout.write(res[i].toString());
        if (i !== res.length - 1)
            process.stdout.write(", ");
    }
    process.stdout.write("]");

Output
[4, 7, 9, 10]

[Expected Approach] Using Simultaneous Inorder Traversal - O(n + m) Time and O(h1 + h2) Space

The idea is to perform inorder traversal of both BSTs simultaneously using two stacks. The inorder traversal of a BST gives nodes in increasing order. Therefore, we can compare the current nodes of both BSTs similar to merging two sorted arrays.

Instead of storing complete inorder traversals, we store only the required nodes in stacks, which reduces extra space usage.

  • Use two stacks to perform simultaneous inorder traversal of both BSTs.
  • Push all left nodes of both BSTs into their respective stacks.
  • Compare the top nodes of both stacks:
  • If values are equal, add it to the result and move to their right subtrees.
  • If the first value is smaller, move ahead in the first BST.
  • Otherwise, move ahead in the second BST.
  • Repeat until either stack becomes empty.
  • Return the result array.
C++
#include <iostream>
#include <vector>
#include <stack>
using namespace std;

// Structure of a BST node.
class Node {
public:
    int data;
    Node *left;
    Node *right;

    Node(int val) {
        data = val;
        left = right = nullptr;
    }
};

// Insert a node into the BST.
Node *insert(Node *root, int key) {
    if (!root)
        return new Node(key);

    if (key < root->data)
        root->left = insert(root->left, key);
    else
        root->right = insert(root->right, key);

    return root;
}

// Function to return the common nodes of two BSTs.
vector<int> findCommon(Node *r1, Node *r2) {

    // Stacks for simultaneous inorder traversal of both BSTs.
    stack<Node *> s1, s2;
    vector<int> res;

    while (true) {

        // Push all left nodes of first BST.
        while (r1) {
            s1.push(r1);
            r1 = r1->left;
        }

        // Push all left nodes of second BST.
        while (r2) {
            s2.push(r2);
            r2 = r2->left;
        }

        // Stop if either traversal is complete.
        if (s1.empty() || s2.empty())
            break;

        Node *curr1 = s1.top();
        Node *curr2 = s2.top();

        if (curr1->data == curr2->data) {

            // Common node found.
            res.push_back(curr1->data);

            s1.pop();
            s2.pop();

            r1 = curr1->right;
            r2 = curr2->right;
        } else if (curr1->data < curr2->data) {

            // Advance in first BST.
            s1.pop();
            r1 = curr1->right;
            r2 = nullptr;
        } else {

            // Advance in second BST.
            s2.pop();
            r2 = curr2->right;
            r1 = nullptr;
        }
    }

    return res;
}

int main() {

    // First BST
    //
    //          5
    //        /   \
    //       1     10
    //      / \    /
    //     0   4  7
    //            \
    //             9
    //
    Node *r1 = nullptr;
    r1 = insert(r1, 5);
    r1 = insert(r1, 1);
    r1 = insert(r1, 10);
    r1 = insert(r1, 0);
    r1 = insert(r1, 4);
    r1 = insert(r1, 7);
    r1 = insert(r1, 9);

    // Second BST
    //
    //        10
    //       /  \
    //      7    20
    //     / \
    //    4   9
    //
    Node *r2 = nullptr;
    r2 = insert(r2, 10);
    r2 = insert(r2, 7);
    r2 = insert(r2, 20);
    r2 = insert(r2, 4);
    r2 = insert(r2, 9);

    vector<int> res = findCommon(r1, r2);

    // Print the array.
    cout << "[";
    for (int i = 0; i < res.size(); i++) {
        cout << res[i];
        if (i != res.size() - 1)
            cout << ", ";
    }
    cout << "]";

    return 0;
}
Java
import java.util.ArrayList;
import java.util.Stack;

// Structure of a BST node.
class Node {
    int data;
    Node left;
    Node right;

    Node(int val) {
        data = val;
        left = right = null;
    }
}

class GFG {

    // Insert a node into the BST.
    static Node insert(Node root, int key) {
        if (root == null)
            return new Node(key);

        if (key < root.data)
            root.left = insert(root.left, key);
        else
            root.right = insert(root.right, key);

        return root;
    }

    // Function to return the common nodes of two BSTs.
    static ArrayList<Integer> findCommon(Node r1, Node r2) {

        // Stacks for simultaneous inorder traversal of both BSTs.
        Stack<Node> s1 = new Stack<>();
        Stack<Node> s2 = new Stack<>();
        ArrayList<Integer> res = new ArrayList<>();

        while (true) {

            // Push all left nodes of first BST.
            while (r1 != null) {
                s1.push(r1);
                r1 = r1.left;
            }

            // Push all left nodes of second BST.
            while (r2 != null) {
                s2.push(r2);
                r2 = r2.left;
            }

            // Stop if either traversal is complete.
            if (s1.isEmpty() || s2.isEmpty())
                break;

            Node curr1 = s1.peek();
            Node curr2 = s2.peek();

            if (curr1.data == curr2.data) {

                // Common node found.
                res.add(curr1.data);

                s1.pop();
                s2.pop();

                r1 = curr1.right;
                r2 = curr2.right;

            } else if (curr1.data < curr2.data) {

                // Advance in first BST.
                s1.pop();
                r1 = curr1.right;
                r2 = null;

            } else {

                // Advance in second BST.
                s2.pop();
                r2 = curr2.right;
                r1 = null;
            }
        }

        return res;
    }

    public static void main(String[] args) {

        // First BST
        //
        //          5
        //        /   \
        //       1     10
        //      / \    /
        //     0   4  7
        //            \
        //             9
        //
        Node r1 = null;
        r1 = insert(r1, 5);
        r1 = insert(r1, 1);
        r1 = insert(r1, 10);
        r1 = insert(r1, 0);
        r1 = insert(r1, 4);
        r1 = insert(r1, 7);
        r1 = insert(r1, 9);

        // Second BST
        //
        //        10
        //       /  \
        //      7    20
        //     / \
        //    4   9
        //
        Node r2 = null;
        r2 = insert(r2, 10);
        r2 = insert(r2, 7);
        r2 = insert(r2, 20);
        r2 = insert(r2, 4);
        r2 = insert(r2, 9);

        ArrayList<Integer> res = findCommon(r1, r2);

        // Print the array.
        System.out.print("[");
        for (int i = 0; i < res.size(); i++) {
            System.out.print(res.get(i));
            if (i != res.size() - 1)
                System.out.print(", ");
        }
        System.out.print("]");
    }
}
Python
# Structure of a BST node.
class Node:
    def __init__(self, val):
        self.data = val
        self.left = None
        self.right = None


# Insert a node into the BST.
def insert(root: 'Node', key: int) -> 'Node':
    if not root:
        return Node(key)

    if key < root.data:
        root.left = insert(root.left, key)
    else:
        root.right = insert(root.right, key)

    return root


# Function to return the common nodes of two BSTs.
def findCommon(r1: 'Node', r2: 'Node') -> list[int]:

    # Stacks for simultaneous inorder traversal of both BSTs.
    s1 = []
    s2 = []
    res = []

    while True:

        # Push all left nodes of first BST.
        while r1:
            s1.append(r1)
            r1 = r1.left

        # Push all left nodes of second BST.
        while r2:
            s2.append(r2)
            r2 = r2.left

        # Stop if either traversal is complete.
        if len(s1) == 0 or len(s2) == 0:
            break

        curr1 = s1[-1]
        curr2 = s2[-1]

        if curr1.data == curr2.data:

            # Common node found.
            res.append(curr1.data)

            s1.pop()
            s2.pop()

            r1 = curr1.right
            r2 = curr2.right

        elif curr1.data < curr2.data:

            # Advance in first BST.
            s1.pop()
            r1 = curr1.right
            r2 = None

        else:

            # Advance in second BST.
            s2.pop()
            r2 = curr2.right
            r1 = None

    return res


if __name__ == "__main__":

    # First BST
    #
    #          5
    #        /   \
    #       1     10
    #      / \    /
    #     0   4  7
    #            \
    #             9
    #
    r1 = None
    r1 = insert(r1, 5)
    r1 = insert(r1, 1)
    r1 = insert(r1, 10)
    r1 = insert(r1, 0)
    r1 = insert(r1, 4)
    r1 = insert(r1, 7)
    r1 = insert(r1, 9)

    # Second BST
    #
    #        10
    #       /  \
    #      7    20
    #     / \
    #    4   9
    #
    r2 = None
    r2 = insert(r2, 10)
    r2 = insert(r2, 7)
    r2 = insert(r2, 20)
    r2 = insert(r2, 4)
    r2 = insert(r2, 9)

    res = findCommon(r1, r2)

    # Print the array.
    print("[", end="")
    for i in range(len(res)):
        print(res[i], end="")
        if i != len(res) - 1:
            print(", ", end="")
    print("]")
C#
using System;
using System.Collections.Generic;

// Structure of a BST node.
class Node
{
    public int data;
    public Node left;
    public Node right;

    public Node(int val)
    {
        data = val;
        left = right = null;
    }
}

class GFG
{
    // Insert a node into the BST.
    static Node insert(Node root, int key)
    {
        if (root == null)
            return new Node(key);

        if (key < root.data)
            root.left = insert(root.left, key);
        else
            root.right = insert(root.right, key);

        return root;
    }

    // Function to return the common nodes of two BSTs.
    static List<int> findCommon(Node r1, Node r2)
    {
        // Stacks for simultaneous inorder traversal of both BSTs.
        Stack<Node> s1 = new Stack<Node>();
        Stack<Node> s2 = new Stack<Node>();
        List<int> res = new List<int>();

        while (true)
        {
            // Push all left nodes of first BST.
            while (r1 != null)
            {
                s1.Push(r1);
                r1 = r1.left;
            }

            // Push all left nodes of second BST.
            while (r2 != null)
            {
                s2.Push(r2);
                r2 = r2.left;
            }

            // Stop if either traversal is complete.
            if (s1.Count == 0 || s2.Count == 0)
                break;

            Node curr1 = s1.Peek();
            Node curr2 = s2.Peek();

            if (curr1.data == curr2.data)
            {
                // Common node found.
                res.Add(curr1.data);

                s1.Pop();
                s2.Pop();

                r1 = curr1.right;
                r2 = curr2.right;
            }
            else if (curr1.data < curr2.data)
            {
                // Advance in first BST.
                s1.Pop();
                r1 = curr1.right;
                r2 = null;
            }
            else
            {
                // Advance in second BST.
                s2.Pop();
                r2 = curr2.right;
                r1 = null;
            }
        }

        return res;
    }

    static void Main()
    {
        // First BST
        //
        //          5
        //        /   \
        //       1     10
        //      / \    /
        //     0   4  7
        //            \
        //             9
        //
        Node r1 = null;
        r1 = insert(r1, 5);
        r1 = insert(r1, 1);
        r1 = insert(r1, 10);
        r1 = insert(r1, 0);
        r1 = insert(r1, 4);
        r1 = insert(r1, 7);
        r1 = insert(r1, 9);

        // Second BST
        //
        //        10
        //       /  \
        //      7    20
        //     / \
        //    4   9
        //
        Node r2 = null;
        r2 = insert(r2, 10);
        r2 = insert(r2, 7);
        r2 = insert(r2, 20);
        r2 = insert(r2, 4);
        r2 = insert(r2, 9);

        List<int> res = findCommon(r1, r2);

        // Print the array.
        Console.Write("[");
        for (int i = 0; i < res.Count; i++)
        {
            Console.Write(res[i]);
            if (i != res.Count - 1)
                Console.Write(", ");
        }
        Console.Write("]");
    }
}
JavaScript
// Structure of a BST node.
class Node {
    constructor(val) {
        this.data = val;
        this.left = null;
        this.right = null;
    }
}

// Insert a node into the BST.
function insert(root, key) {
    if (!root)
        return new Node(key);

    if (key < root.data)
        root.left = insert(root.left, key);
    else
        root.right = insert(root.right, key);

    return root;
}

// Function to return the common nodes of two BSTs.
function findCommon(r1, r2) {

    // Stacks for simultaneous inorder traversal of both BSTs.
    let s1 = [];
    let s2 = [];
    let res = [];

    while (true) {

        // Push all left nodes of first BST.
        while (r1) {
            s1.push(r1);
            r1 = r1.left;
        }

        // Push all left nodes of second BST.
        while (r2) {
            s2.push(r2);
            r2 = r2.left;
        }

        // Stop if either traversal is complete.
        if (s1.length === 0 || s2.length === 0)
            break;

        let curr1 = s1[s1.length - 1];
        let curr2 = s2[s2.length - 1];

        if (curr1.data === curr2.data) {

            // Common node found.
            res.push(curr1.data);

            s1.pop();
            s2.pop();

            r1 = curr1.right;
            r2 = curr2.right;
        }
        else if (curr1.data < curr2.data) {

            // Advance in first BST.
            s1.pop();
            r1 = curr1.right;
            r2 = null;
        }
        else {

            // Advance in second BST.
            s2.pop();
            r2 = curr2.right;
            r1 = null;
        }
    }

    return res;
}
// Driver code

    // First BST
    //
    //          5
    //        /   \
    //       1     10
    //      / \    /
    //     0   4  7
    //            \
    //             9
    //
    let r1 = null;
    r1 = insert(r1, 5);
    r1 = insert(r1, 1);
    r1 = insert(r1, 10);
    r1 = insert(r1, 0);
    r1 = insert(r1, 4);
    r1 = insert(r1, 7);
    r1 = insert(r1, 9);

    // Second BST
    //
    //        10
    //       /  \
    //      7    20
    //     / \
    //    4   9
    //
    let r2 = null;
    r2 = insert(r2, 10);
    r2 = insert(r2, 7);
    r2 = insert(r2, 20);
    r2 = insert(r2, 4);
    r2 = insert(r2, 9);

    let res = findCommon(r1, r2);

    // Print the array.
    process.stdout.write("[");

    for (let i = 0; i < res.length; i++) {
        process.stdout.write(res[i].toString());

        if (i !== res.length - 1)
            process.stdout.write(", ");
    }

    process.stdout.write("]");

Output
[4, 7, 9, 10]
Comment