Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

In the following, B1 and B2 are two binary search trees such that every key in B

ID: 3667047 • Letter: I

Question

In the following, B1 and B2 are two binary search trees such that every key in B1 is smaller than every key in B2. Describe an algorithm that, given pointers b1 and b2 to the roots of B1 and B2, merges B1 and B2 into a single binary search tree T. Your algorithm should satisfy the following two properties: 1. Its worst–case running time is O(min{h1, h2}), where h1 and h2 are the heights of B1 and B2. 2. The height of the merged tree T is at most max{h1, h2} + 1. Note that the heights h1 and h2 are not given to the algorithm (in other words, the algorithm does not “know” the heights of B1 and B2). Note also that B1, B2 and T are not required to be balanced. Describe your algorithm, and justify its correctness and worst-case running time, in clear and concise English. Note: Partial credit may be given for an algorithm that runs in O(max{h1, h2}) time.

Explanation / Answer

The below shown code describes joining two BST's by using insertion at root (which in turn uses left and right rotations): template struct Node { T value; Node* left; Node* right; explicit Node(T v) : value(v), left(NULL), right(NULL) { } }; template Node* rotate_right(Node* node) { if (node) { if (Node* left = node->left) { node->left = left->right; left->right = node; node = left; } } return node; } template Node* rotate_left(Node* node) { if (node) { if (Node* right = node->right) { node->right = right->left; right->left = node; node = right; } } return node; } template Node* insert_at_root(Node* tree, Node& node) { if (tree) { if (tree->value >= node.value) { tree->left = insert_at_root(tree->left, node); return rotate_right(tree); } else if (tree->value right = insert_at_root(tree->right, node); return rotate_left(tree); } } node.left = node.right = NULL; return &node; } template Node* join(Node* left, Node* right) { Node* node = right; if (left) { //save left and right links, insert_at_roots nulls them out Node* tmp_left = left->left; Node* tmp_right = left->right; node = insert_at_root(right, *left); node->left = join(tmp_left, node->left); node->right = join(tmp_right, node->right); } return node; }
Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote