The Wayback Machine - https://web.archive.org/web/20240917142708/https://www.geeksforgeeks.org/construct-all-possible-bsts-for-keys-1-to-n/
Open In App

Construct all possible BSTs for keys 1 to N

Last Updated : 28 Dec, 2022
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

In this article, first count of possible BST (Binary Search Trees)s is discussed, then the construction of all possible BSTs.

How many structurally unique BSTs for keys from 1..N? 

For example, for N = 2, there are 2 unique BSTs
     1               2  
      \            /
       2         1 

For N = 3, there are 5 possible BSTs
  1              3        3         2      1
    \           /        /        /  \      \
     3        2         1        1    3      2
    /       /            \                    \
   2      1               2                    3

We strongly recommend you to minimize your browser and try this yourself first.
We know that all node in left subtree are smaller than root and in right subtree are larger than root so if we have ith number as root, all numbers from 1 to i-1 will be in left subtree and i+1 to N will be in right subtree. If 1 to i-1 can form x different trees and i+1 to N can from y different trees then we will have x*y total trees when ith number is root and we also have N choices for root also so we can simply iterate from 1 to N for root and another loop for left and right subtree. If we take a closer look, we can notice that the count is basically n’th Catalan number. We have discussed different approaches to find n’th Catalan number here. 

How to construct all BST for keys 1..N? 
The idea is to maintain a list of roots of all BSTs. Recursively construct all possible left and right subtrees. Create a tree for every pair of left and right subtree and add the tree to list. Below is detailed algorithm. 

  1. Initialize list of BSTs as empty.  
  2. For every number i where i varies from 1 to N, do following
    • Create a new node with key as ‘i’, let this node be ‘node’
    • Recursively construct list of all left subtrees.
    • Recursively construct list of all right subtrees.
  3. Iterate for all left subtrees
    • For current leftsubtree, iterate for all right subtrees
    • Add current left and right subtrees to ‘node’ and add
    • node’ to list.

Below is the implementation of the above idea. 

C++




// A C++ program to construct all unique BSTs for keys from 1 to n
#include <bits/stdc++.h>
using namespace std;
 
//  node structure
struct node
{
    int key;
    struct node *left, *right;
};
 
// A utility function to create a new BST node
struct node *newNode(int item)
{
    struct node *temp =  new node;
    temp->key = item;
    temp->left = temp->right = NULL;
    return temp;
}
 
// A utility function to do preorder traversal of BST
void preorder(struct node *root)
{
    if (root != NULL)
    {
        cout << root->key << " ";
        preorder(root->left);
        preorder(root->right);
    }
}
 
//  function for constructing trees
vector<struct node *> constructTrees(int start, int end)
{
    vector<struct node *> list;
 
    /*  if start > end   then subtree will be empty so returning NULL
        in the list */
    if (start > end)
    {
        list.push_back(NULL);
        return list;
    }
 
    /*  iterating through all values from start to end  for constructing\
        left and right subtree recursively  */
    for (int i = start; i <= end; i++)
    {
        /*  constructing left subtree   */
        vector<struct node *> leftSubtree  = constructTrees(start, i - 1);
 
        /*  constructing right subtree  */
        vector<struct node *> rightSubtree = constructTrees(i + 1, end);
 
        /*  now looping through all left and right subtrees and connecting
            them to ith root  below  */
        for (int j = 0; j < leftSubtree.size(); j++)
        {
            struct node* left = leftSubtree[j];
            for (int k = 0; k < rightSubtree.size(); k++)
            {
                struct node * right = rightSubtree[k];
                struct node * node = newNode(i);// making value i as root
                node->left = left;              // connect left subtree
                node->right = right;            // connect right subtree
                list.push_back(node);           // add this tree to list
            }
        }
    }
    return list;
}
 
// Driver Program to test above functions
int main()
{
    // Construct all possible BSTs
    vector<struct node *> totalTreesFrom1toN = constructTrees(1, 3);
 
 
    /*  Printing preorder traversal of all constructed BSTs   */
    cout << "Preorder traversals of all constructed BSTs are \n";
    for (int i = 0; i < totalTreesFrom1toN.size(); i++)
    {
        preorder(totalTreesFrom1toN[i]);
        cout << endl;
    }
    return 0;
}


Java




// A Java program to construct all unique BSTs for keys from 1 to n
import java.util.ArrayList;
public class Main {
 
    //  function for constructing trees
    static ArrayList<Node> constructTrees(int start, int end)
    {
        ArrayList<Node> list=new ArrayList<>();
        /*  if start > end   then subtree will be empty so returning NULL
            in the list */
        if (start > end)
        {
            list.add(null);
            return list;
        }
   
        /*  iterating through all values from start to end  for constructing\
            left and right subtree recursively  */
        for (int i = start; i <= end; i++)
        {
            /*  constructing left subtree   */
            ArrayList<Node> leftSubtree  = constructTrees(start, i - 1);
   
            /*  constructing right subtree  */
            ArrayList<Node> rightSubtree = constructTrees(i + 1, end);
   
            /*  now looping through all left and right subtrees and connecting
                them to ith root  below  */
            for (int j = 0; j < leftSubtree.size(); j++)
            {
                Node left = leftSubtree.get(j);
                for (int k = 0; k < rightSubtree.size(); k++)
                {
                    Node right = rightSubtree.get(k);
                    Node node = new Node(i);        // making value i as root
                    node.left = left;              // connect left subtree
                    node.right = right;            // connect right subtree
                    list.add(node);                // add this tree to list
                }
            }
        }
        return list;
    }
 
    // A utility function to do preorder traversal of BST
    static void preorder(Node root)
    {
        if (root != null)
        {
            System.out.print(root.key+" ") ;
            preorder(root.left);
            preorder(root.right);
        }
    }
 
    public static void main(String args[])
    {
        ArrayList<Node> totalTreesFrom1toN = constructTrees(1, 3);
        /*  Printing preorder traversal of all constructed BSTs   */
        System.out.println("Preorder traversals of all constructed BSTs are ");
        for (int i = 0; i < totalTreesFrom1toN.size(); i++)
        {
            preorder(totalTreesFrom1toN.get(i));
            System.out.println();
        }
    }
}
 
//  node structure
class Node
{
    int key;
    Node left, right;
    Node(int data)
    {
        this.key=data;
        left=right=null;
    }
};
//This code is contributed by Gaurav Tiwari


Python3




# Python3 program to construct all unique
# BSTs for keys from 1 to n
 
# Binary Tree Node
""" A utility function to create a
new BST node """
class newNode:
 
    # Construct to create a newNode
    def __init__(self, item):
        self.key=item
        self.left = None
        self.right = None
 
# A utility function to do preorder
# traversal of BST
def preorder(root) :
 
    if (root != None) :
     
        print(root.key, end = " " )
        preorder(root.left)
        preorder(root.right)
     
# function for constructing trees
def constructTrees(start, end):
 
    list = []
 
    """ if start > end then subtree will be
        empty so returning None in the list """
    if (start > end) :
     
        list.append(None)
        return list
     
    """ iterating through all values from
        start to end for constructing
        left and right subtree recursively """
    for i in range(start, end + 1):
     
        """ constructing left subtree """
        leftSubtree = constructTrees(start, i - 1)
 
        """ constructing right subtree """
        rightSubtree = constructTrees(i + 1, end)
 
        """ now looping through all left and
            right subtrees and connecting
            them to ith root below """
        for j in range(len(leftSubtree)) :
            left = leftSubtree[j]
            for k in range(len(rightSubtree)):
                right = rightSubtree[k]
                node = newNode(i)   # making value i as root
                node.left = left    # connect left subtree
                node.right = right    # connect right subtree
                list.append(node)    # add this tree to list
    return list
 
# Driver Code
if __name__ == '__main__':
 
    # Construct all possible BSTs
    totalTreesFrom1toN = constructTrees(1, 3)
 
    """ Printing preorder traversal of
        all constructed BSTs """
    print("Preorder traversals of all",
                "constructed BSTs are")
    for i in range(len(totalTreesFrom1toN)):
        preorder(totalTreesFrom1toN[i])
        print()
 
# This code is contributed by
# Shubham Singh(SHUBHAMSINGH10)


C#




// C# program to construct all
// unique BSTs for keys from 1 to n
using System.Collections;
using System;
 
class GFG
{
 
    // function for constructing trees
    static ArrayList constructTrees(int start, int end)
    {
        ArrayList list = new ArrayList();
         
        /* if start > end then subtree will
        be empty so returning NULL
        in the list */
        if (start > end)
        {
            list.Add(null);
            return list;
        }
     
        /* iterating through all values from
        start to end for constructing\
        left and right subtree recursively */
        for (int i = start; i <= end; i++)
        {
            /* constructing left subtree */
            ArrayList leftSubtree = constructTrees(start, i - 1);
     
            /* constructing right subtree */
            ArrayList rightSubtree = constructTrees(i + 1, end);
     
            /* now looping through all left and
            right subtrees and connecting
            them to ith root below */
            for (int j = 0; j < leftSubtree.Count; j++)
            {
                Node left = (Node)leftSubtree[j];
                for (int k = 0; k < rightSubtree.Count; k++)
                {
                    Node right = (Node)rightSubtree[k];
                     
                    // making value i as root
                    Node node = new Node(i);
                     
                    // connect left subtree
                    node.left = left;
                     
                    // connect right subtree
                    node.right = right;    
                     
                    // Add this tree to list
                    list.Add(node);        
                }
            }
        }
        return list;
    }
 
    // A utility function to do
    // preorder traversal of BST
    static void preorder(Node root)
    {
        if (root != null)
        {
            Console.Write(root.key+" ") ;
            preorder(root.left);
            preorder(root.right);
        }
    }
 
    // Driver code
    public static void Main(String []args)
    {
        ArrayList totalTreesFrom1toN = constructTrees(1, 3);
         
        /* Printing preorder traversal
        of all constructed BSTs */
        Console.WriteLine("Preorder traversals of all" +
                                "constructed BSTs are ");
        for (int i = 0; i < totalTreesFrom1toN.Count; i++)
        {
            preorder((Node)totalTreesFrom1toN[i]);
            Console.WriteLine();
        }
    }
     
// node structure
public class Node
{
    public int key;
    public Node left, right;
    public Node(int data)
    {
        this.key=data;
        left=right=null;
    }
};
}
 
// This code is contributed by Arnab Kundu


Javascript




<script>
 
 
// node structure
class Node
{
    constructor(data)
    {
        this.key = data;
        this.left = null;
        this.right = null;
    }
};
 
// Javascript program to construct all
// unique BSTs for keys from 1 to n
// function for constructing trees
function constructTrees(start, end)
{
    var list = [];
     
    /* if start > end then subtree will
    be empty so returning NULL
    in the list */
    if (start > end)
    {
        list.push(null);
        return list;
    }
 
    /* iterating through all values from
    start to end for constructing\
    left and right subtree recursively */
    for (var i = start; i <= end; i++)
    {
        /* constructing left subtree */
        var leftSubtree = constructTrees(start, i - 1);
 
        /* constructing right subtree */
        var rightSubtree = constructTrees(i + 1, end);
 
        /* now looping through all left and
        right subtrees and connecting
        them to ith root below */
        for (var j = 0; j < leftSubtree.length; j++)
        {
            var left = leftSubtree[j];
            for (var k = 0; k < rightSubtree.length; k++)
            {
                var right = rightSubtree[k];
                 
                // making value i as root
                var node = new Node(i);
                 
                // connect left subtree
                node.left = left;
                 
                // connect right subtree
                node.right = right;    
                 
                // push this tree to list
                list.push(node);        
            }
        }
    }
    return list;
}
 
// A utility function to do
// preorder traversal of BST
function preorder(root)
{
    if (root != null)
    {
        document.write(root.key+" ") ;
        preorder(root.left);
        preorder(root.right);
    }
}
// Driver code
var totalTreesFrom1toN = constructTrees(1, 3);
 
/* Printing preorder traversal
of all constructed BSTs */
document.write("Preorder traversals of all" +
                        "constructed BSTs are<br>");
for (var i = 0; i < totalTreesFrom1toN.length; i++)
{
    preorder(totalTreesFrom1toN[i]);
    document.write("<br>");
}
 
 
 
</script>


Output

Preorder traversals of all constructed BSTs are 
1 2 3 
1 3 2 
2 1 3 
3 1 2 
3 2 1 

Time Complexity: O(2^n).

The time complexity of this solution is exponential. This is because we are constructing all possible BSTs. Since at each level, we are generating two subproblems and at each level, there are O(2^n) subproblems, the time complexity is O(2^n).

Auxiliary Space: O(2^n).

The space complexity of this solution is also exponential. This is because we are constructing all possible BSTs. Since at each level, we are generating two subproblems and at each level, there are O(2^n) subproblems, the space complexity is O(2^n).



Previous Article
Next Article

Similar Reads

Check if two given key sequences construct same BSTs
Given two arrays which represent two sequences of keys that are used to create BSTs. Imagine we make a Binary Search Tree (BST) from each array. We need to tell whether two BSTs will be identical or not without actually constructing the tree. Examples: Let the input arrays be a[] and b[] Example 1: a[] = {2, 4, 1, 3} will construct following tree.
6 min read
Print all pairs from two BSTs whose sum is greater than the given value
Given two Binary Search Tree (BSTs) and a value X, the problem is to print all pairs from both the BSTs whose sum is greater than the given value X.\ Examples: Input: BST 1: 5 / \ 3 7 / \ / \ 2 4 6 8 BST 2: 10 / \ 6 15 / \ / \ 3 8 11 18X = 20Output: The pairs are: (3, 18) (4, 18) (5, 18) (6, 18) (7, 18) (8, 18) (6, 15) (7, 15) (8, 15)Naive Approach
15+ min read
Check for Identical BSTs without building the trees
Given two arrays that represent a sequence of keys. Imagine we make a Binary Search Tree (BST) from each array. We need to tell whether two BSTs will be identical or not without actually constructing the tree. Example: For example, the input arrays are {2, 4, 3, 1} and {2, 1, 4, 3} will construct the same tree Let the input arrays be a[] and b[] Ex
15 min read
Split a BST into two balanced BSTs based on a value K
Given a Binary Search tree and an integer K, we have to split the tree into two Balanced Binary Search Tree, where BST-1 consists of all the nodes which are less than K and BST-2 consists of all the nodes which are greater than or equal to K.Note: The arrangement of the nodes may be anything but both BST should be Balanced. Examples: Input: 40 / \
15+ min read
Generate two BSTs from the given array such that maximum height among them is minimum
Given an array of n integers where n is greater than 1, the task is to make two Binary Search Tree from the given array (in any order) such that the maximum height among the two trees is minimum possible and print the maximum height.Examples: Input: arr[] = {1, 2, 3, 4, 6} Output: 1 Input: arr[] = { 74, 25, 23, 1, 65, 2, 8, 99 } Output: 2 Approach:
4 min read
Nodes from given two BSTs with sum equal to X
Given two Binary search trees and an integer X, the task is to find a pair of nodes, one belonging to the first BST and the second belonging to other such that their sum is equal to X. If there exists such a pair, print Yes else print No. Examples: Input: X = 100 BST 1: 5 / \ 3 7 / \ / \ 2 4 6 8 BST 2: 11 \ 13 Output: No There is no such pair with
9 min read
Total number of BSTs using array elements
Prerequisite: Total number of possible Binary Search Trees with n keys Given an array arr[] of N integers. The task is to count the number of Binary Search Tree can be made using each node of element in arr[] as a root node.Examples: Input: arr[] = { 20, 10, 30 } Output: 1 2 2 Input: arr[] = { 1, 2, 3, 4, 5 } Output: 14 5 4 5 14 Approach: The total
7 min read
Count of BSTs with N nodes having height at least K
Given two positive integers N and K, the task is to find the number of binary search trees (BST) with N nodes of height greater than or equal to K. Note: Here height refers to the maximum depth of the BST. Examples: Input: N = 3, K = 3Output: 4Explanation:There are 4 possible binary search trees with height greater than or equal to K. 1 1 3 3 \ \ /
6 min read
Count of BSTs having N nodes and maximum depth equal to H
Given two integers N and H, the task is to find the count of distinct Binary Search Trees consisting of N nodes where the maximum depth or height of the tree is equal to H. Note: The height of BST with only the root node is 0. Examples: Input: N = 2, H = 1Output: 2Explanation: The two BST's are : Input: N = 3, H = 2Output: 4Explanation: The four BS
15+ min read
Count pairs from two BSTs whose sum is equal to a given value x
Given two BSTs containing n1 and n2 distinct nodes respectively. Given a value x. The problem is to count all pairs from both the BSTs whose sum is equal to x. Examples: Input : BST 1: 5 / \ 3 7 / \ / \ 2 4 6 8 BST 2: 10 / \ 6 15 / \ / \ 3 8 11 18 x = 16 Output : 3 The pairs are: (5, 11), (6, 10) and (8, 8)Recommended PracticeBrothers From Differen
15+ min read
Merge two BSTs with limited extra space
Given two Binary Search Trees(BST), print the inorder traversal of merged BSTs. Examples: Input: First BST 3 / \ 1 5Second BST 4 / \2 6Output: 1 2 3 4 5 6 Input:First BST 8 / \ 2 10 / 1Second BST 5 / 3 /0Output: 0 1 2 3 5 8 10 Recommended PracticeMerge two BST 'sTry It!Merge two BSTs using Iterative Inorder Traversal: The idea is to use iterative i
15+ min read
Find pairs with given sum such that pair elements lie in different BSTs
Given two Binary Search Trees (BST) and a given sum. The task is to find pairs with given sum such that each pair elements must lie in different BST. Examples: Input : sum = 10 8 5 / \ / \ 3 10 2 18 / \ \ / \ 1 6 14 1 3 / \ / \ 5 7 13 4 Output : (5,5), (6,4), (7,3), (8,2) In above pairs first element lies in first BST and second element lies in sec
14 min read
Check if two BSTs contain same set of elements
Given two Binary Search Trees consisting of unique positive elements, we have to check whether the two BSTs contain the same set of elements or not. Note: The structure of the two given BSTs can be different. For example, The above two BSTs contains same set of elements {5, 10, 12, 15, 20, 25} Method 1: The most simple method will be to traverse fi
15 min read
Different ways of sorting Dictionary by Keys and Reverse sorting by keys
Prerequisite: Dictionaries in Python A dictionary is a collection which is unordered, changeable and indexed. In Python, dictionaries are written with curly brackets, and they have keys and values. We can access the values of the dictionary using keys. In this article, we will discuss 10 different ways of sorting the Python dictionary by keys and a
8 min read
Construct string having all possible strings of K letters as subsequence
Given two positive integers, let's denote them as N and K. The task is to construct a string S such that all possible strings of length N formed using the first K lowercase English alphabets, appear as subsequences of S. In case there exist multiple valid solutions, the objective is to output the solution with the minimal length. If there are still
4 min read
Construct the smallest possible Array with given Sum and XOR
Given two positive integers S and X which represents the sum and Bitwise XOR of all the elements of an array arr[]. The task is to find the elements of the array arr[]. If no such array can be generated, print -1.Examples: Input: Sum = 4, Xor = 2 Output: {3, 1} Explanation: Sum of 1 and 3 is 4. Bitwise XOR of 1 and 3 is 2.Input: Sum = 5, Xor = 8 Ou
7 min read
Construct an AP series consisting of A and B having minimum possible Nth term
Given two integers A, B which are any two terms of an Arithmetic Progression series, and an integer N, the task is to construct an Arithmetic Progression series of size N such that it must include both A and B and the Nth term of the AP should be minimum. Examples: Input: N = 5, A = 20, B = 50Output: 10 20 30 40 50Explanation:One of the possible AP
11 min read
Construct smallest N-digit number possible by placing digits at positions specified by given array
Given two integers N and M and an 2D array arr[], the task is to construct the smallest possible integer of N digits ( without leading zeroes ) such that the arr[i][0]th digit from the left is arr[i][1]. If it is not possible to construct any such integer, print "No". Otherwise, print that number. Examples: Input : N = 3, arr[]={{0, 7}, {2, 2}}Outp
14 min read
Construct longest possible sequence of unique elements with given LCM
Given a positive integer N, the task is to construct the longest sorted sequence of unique elements whose LCM of the is equal to N. Examples: Input: N = 12 Output: 1 2 3 4 6 12 Explanation: LCM of {1, 2, 3, 4, 6, 12 } is N( = 12). Therefore, the longest possible sequence is {1, 2, 3, 4, 6, 12 }. Input: N = 9 Output: 1 3 9 Explanation: LCM of { 1, 2
5 min read
Check if it is possible to construct an Array of size N having sum as S and XOR value as X
Given three numbers N, S and X the task is to find if it is possible to construct a sequence A of length N, where each A[i] &gt;= 0 for 1&lt;=i&lt;=N and the sum of all numbers in a sequence is equal to S, and the bit-wise XOR of sequence equals to X. Examples: Input: N = 3, S = 10, X = 4 Output: YesExplanation: One of the sequence possible is {4,
10 min read
Check if it is possible to construct an array with the given conditions
Given integers N and K and an array A[] of M integers. The task is to check if it is possible to construct an array of size N such that- All the K consecutive elements of the array are distinct.Considering 1-based indexing, the integer i can be used A[i] times to construct the array.Note that sum of all elements of array is A[] is guaranteed to be
9 min read
Count possible ways to construct buildings
Given an input number of sections and each section has 2 plots on either sides of the road. Find all possible ways to construct buildings in the plots such that there is a space between any 2 buildings. Example : N = 1 Output = 4 Place a building on one side. Place a building on other side Do not place any building. Place a building on both sides.
11 min read
Program to construct a DFA which accepts the language having all 'a' before all 'b'
Given a string S, the task is to design a Deterministic Finite Automata (DFA) for accepting the language L = {aNbM | N ≥ 0, M ≥ 0, N+M ≥ 1}. , i.e., a regular language L such that all 'a' occur before the first occurrence of 'b' {a, ab, aab, bb..., }. If the given string follows the given language L, then print “Accepted”. Otherwise, print “Not Acc
8 min read
Total number of possible Binary Search Trees and Binary Trees with n keys
Total number of possible Binary Search Trees with n different keys (countBST(n)) = Catalan number Cn = (2n)! / ((n + 1)! * n!) For n = 0, 1, 2, 3, … values of Catalan numbers are 1, 1, 2, 5, 14, 42, 132, 429, 1430, 4862, .... So are numbers of Binary Search Trees. Total number of possible Binary Trees with n different keys (countBT(n)) = countBST(n
12 min read
Minimum LCM and GCD possible among all possible sub-arrays
Given an array arr[] of N positive integers, the task is to find the minimum LCM and GCD between elements of all possible sub-array.Examples: Input: arr[] = {4, 4, 8} Output: LCM = 4, GCD = 4 All possible sub-arrays are: {4} -&gt; LCM = 4, GCD = 4 {8} -&gt; LCM = 8, GCD = 8 {4, 8} -&gt; LCM = 8, GCD = 4Input: arr[] = {2, 66, 14, 521} Output: LCM =
6 min read
Sum of all possible expressions of a numeric string possible by inserting addition operators
Given a numeric string str of length N, the task is to find the sum of all possible expressions by inserting the '+' operator between the characters of the string any number of times. Examples: Input: str = "125" Output: 176 Explanation: Inserting "+" after 1st index modifies str to "1+25" and value = 26 Inserting "+" after 2nd index modifies str t
8 min read
Construct a graph from given degrees of all vertices
This is a C++ program to generate a graph for a given fixed degree sequence. This algorithm generates a undirected graph for the given degree sequence.It does not include self-edge and multiple edges. Examples: Input : degrees[] = {2, 2, 1, 1} Output : (0) (1) (2) (3) (0) 0 1 1 0 (1) 1 0 0 1 (2) 1 0 0 0 (3) 0 1 0 0 Explanation : We are given that t
7 min read
Construct an Array of size N whose sum of cube of all elements is a perfect square
Given an integer N, the tasks is to construct a sorted array arr[] of size N, such that the sum of cube of all elements is a perfect square, i.e. [Tex]\sum_{}A_i^3=X^2 [/Tex], where X is an integer. Examples: Input: N = 5 Output: 1 2 3 4 5 Explanation Sum of cube of all elements = 1 + 8 + 27 + 64 + 125 = 225 which is a perfect square number. Input:
3 min read
Construct an Array such that cube sum of all element is a perfect square
Given the size of array N, the task is to construct an array of size N with positive integer elements such that the cube sum of all elements of this array is a perfect square.Note: Repetitions of integers are allowed.Example: Input: N = 1 Output: 4 Explanation: Cube of 4 is 64, and 64 is perfect square.Input: N = 6 Output: 5 10 5 10 5 5 Explanation
4 min read
Construct original array starting with K from an array of XOR of all elements except elements at same index
Given an array A[] consisting of N integers and first element of the array B[] as K, the task is to construct the array B[] from A[] such that for any index i, A[i] is the Bitwise XOR of all the array elements of B[] except B[i]. Examples: Input: A[] = {13, 14, 10, 6}, K = 2Output: 2 1 5 9Explanation:For any index i, A[i] is the Bitwise XOR of all
6 min read