/** * This function merges two balanced BSTs with roots as root1 and root2. * m and n are the sizes of the trees respectively */ struct node* mergeTrees(struct node *root1, struct node *root2, int m, int n) { /** * Store inorder traversal of first tree in an array arr1[] */ int *arr1 = new int[m]; int i = 0; storeInorder(root1, arr1, &i); /** * Store inorder traversal of second tree in another array arr2[] */ int *arr2 = new int[n]; int j = 0; storeInorder(root2, arr2, &j); /** * Merge the two sorted array into one */ int *mergedArr = merge(arr1, arr2, m, n); /** * Construct a tree from the merged array and return root of the tree */ return sortedArrayToBST(mergedArr, 0, m+n-1); }
/** * A helper function that stores inorder traversal of a tree in inorder array */ void storeInorder(struct node* node, int inorder[], int *index_ptr) { if (node == NULL) return ; storeInorder(node->left, inorder, index_ptr); inorder[*index_ptr] = node->data; (*index_ptr)++; storeInorder(node->right, inorder, index_ptr); }
/* A helper function that stores inorder traversal of a tree rooted with node */ void storeInorder (struct node* node, int inorder[], int *index_ptr) { // Base Case if (node == NULL) return; /* first store the left subtree */ storeInorder (node->left, inorder, index_ptr); /* Copy the root's data */ inorder[*index_ptr] = node->data; (*index_ptr)++; // increase index for next entry /* finally store the right subtree */ storeInorder (node->right, inorder, index_ptr); }
// This function converts a given Binary Tree to BST void binaryTreeToBST (struct node *root) { // base case: tree is empty if(root == NULL) return; /* Count the number of nodes in Binary Tree so that we know the size of temporary array to be created */ int n = countNodes (root); // Create a temp array arr[] and store inorder traversal of tree in arr[] int *arr = new int[n]; int i = 0; storeInorder (root, arr, &i); // Sort the array using library function for quick sort qsort (arr, n, sizeof(arr[0]), compare); // Copy array elements back to Binary Tree i = 0; arrayToBST (arr, root, &i); // delete dynamically allocated memory to avoid meory leak delete [] arr; }