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
- Subtree of all nodes in a tree using DFS
- Even size subtree in n-ary tree
- Queries for M-th node in the DFS of subtree
- Subtree with given sum in a Binary Tree
- Queries for DFS of a subtree in a tree
- Duplicate subtree in Binary Tree | SET 2
- Find largest subtree sum in a tree
- Euler Tour | Subtree Sum using Segment Tree
- Check if the given Binary Tree have a Subtree with equal no of 1's and 0's
- Find the Kth node in the DFS traversal of a given subtree in a Tree
- Find the largest BST subtree in a given Binary Tree | Set 1
- Check if two nodes are in same subtree of the root node
- Find largest subtree having identical left and right subtrees
- Find the largest Complete Subtree in a given Binary Tree
- Number of leaf nodes in the subtree of every node of an n-ary tree
This article is contributed by Team Geeksforgeeks. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.