Sudo Placement[1.4] | Jumping the Subtree
Given a binary search tree of n nodes with distinct values. Also given are Q queries. Each query consists of a node value that has to be searched in the BST and skip the subtree that has given node as its root. If the provided node is the root itself then print “Empty” without quotes. After that print the preorder traversal of the BST.
Input: N = 7, Q = 2 BST elements: 8 4 10 15 14 88 64 Query1: 15 Query2: 88 Output: 8 4 10 8 4 10 15 14 The tree below will be formed from the elements given 8 / \ 4 10 \ 15 / \ 14 88 / 64 Query1 = 15. So, skip the subtree with 15 as root. The remaining tree is : 8 / \ 4 10 The preorder traversal of the above tree is: 8 4 10 Query2 = 88. So we skip the subtree with 88 as root. The remaining tree is : 8 / \ 4 10 \ 15 / 14 The preorder traversal of the above tree is: 8 4 10 15 14
A naive approach is to traverse the entire tree and store its pre-order traversal. In every query, perform a pre-order traversal treating node as root. Print the entire tree’s pre-order traversal except the elements that are in the pre-order traversal of the tree which treats node as the root.
An efficient approach is to store the entire pre-order traversal of the tree in a container. While finding the pre-order traversal of the tree, store the number of recursive calls from the node and store it in a hash-table(mp). This effectively stores the entire size of the subtree treating any node as the root. While performing every query, print the pre-order traversal of the tree, till the node is found, once it is found, perform a jump of mp[node] steps so that the subtree is skipped.
Below is the implementation of the above approach:
8 4 10 8 4 10 15 14