Restoring BST Structure from Leaf Removal Sequences
Last Updated :
10 Jun, 2024
Given a sequence of strings representing the leaf nodes removed from a Binary Search Tree (BST) in multiple iterations, reconstruct the original BST and print its pre-order traversal. Each string in the array contains the leaf nodes removed in one iteration. The task is to determine the pre-order traversal of the reconstructed BST.
Example:
Input: {“BDHPY”,”CM”,”GQ”,”K”}
Output: KGCBDHQMPY
Input: {“K”}
Output: K
Approach:
The key is to reverse-engineer the tree by reinserting the nodes in the opposite order of their removal. Starting from the last set of removed leaf nodes and moving backwards, we collect all unique nodes in reverse order. This ensures that we rebuild the BST correctly.
The process begins by initializing an empty set to track all unique nodes and an array to maintain the nodes in the reverse order of their removal. We iterate through the input strings from the last to the first, and for each node in these strings, we add it to our set and vector if it hasn't been added before. This step ensures that we handle each node only once.
Next, we construct the BST by inserting nodes from the array in sequence. Each insertion follows the BST property, where for any given node, nodes with smaller values are placed on the left subtree and nodes with larger values on the right subtree. This reconstruction accurately reflects the original tree structure before any nodes were removed.
Finally, we perform a pre-order traversal of the reconstructed BST. In pre-order traversal, we visit the root node first, followed by the left subtree, and then the right subtree. This traversal order gives us the desired output.
Step-by-Step Approach:
- Start with the strings in the input array, representing the leaf nodes removed in each iteration.
- Reconstruct the BST:
- Initialize an empty BST.
- Insert nodes back into the BST in the reverse order of their removal (i.e., from the last string to the first).
- Ensure that the insertion maintains the BST properties.
- Perform a pre-order traversal of the reconstructed BST and print the result.
Below is the implementation of the above approach:
C++
#include <iostream>
#include <string>
#include <unordered_set>
#include <vector>
using namespace std;
// Node structure for BST
struct TreeNode {
char val;
TreeNode *left, *right;
TreeNode(char x)
: val(x)
, left(NULL)
, right(NULL)
{
}
};
// Function to insert a node into the BST
TreeNode* insertNode(TreeNode* root, char val)
{
if (!root)
return new TreeNode(val);
if (val < root->val) {
root->left = insertNode(root->left, val);
}
else {
root->right = insertNode(root->right, val);
}
return root;
}
// Function for pre-order traversal
void preOrderTraversal(TreeNode* root, string& result)
{
if (!root)
return;
result += root->val;
preOrderTraversal(root->left, result);
preOrderTraversal(root->right, result);
}
// Main function to build the BST and print pre-order
// traversal
void printPreOrderTraversal(vector<string> leaves)
{
unordered_set<char> allNodes;
vector<char> nodesInReverseOrder;
// Collect all unique nodes and maintain reverse order
// of their removal
for (auto it = leaves.rbegin(); it != leaves.rend();
++it) {
for (char node : *it) {
if (allNodes.find(node) == allNodes.end()) {
allNodes.insert(node);
nodesInReverseOrder.push_back(node);
}
}
}
TreeNode* root = NULL;
// Insert nodes in reverse order of leaf removal
for (char node : nodesInReverseOrder) {
root = insertNode(root, node);
}
// Get pre-order traversal
string result = "";
preOrderTraversal(root, result);
cout << result << endl;
}
// Driver code
int main()
{
vector<string> input1 = { "BDHPY", "CM", "GQ", "K" };
cout << printPreOrderTraversal(input1);
return 0;
}
OutputOutput for Input 1: KGCBDHQMPY
Time Complexity:
- Collecting unique nodes: O(n), where n is the total number of characters across all strings.
- Inserting nodes into the BST: O(n log n) in the average case.
- Pre-order traversal: O(n).
Auxiliary Space Complexity:
- O(n) for storing the nodes and the call stack for traversal.
Similar Reads
Leaf nodes from Preorder of a Binary Search Tree (Using Recursion) Given Preorder traversal of a Binary Search Tree. Then the task is to print leaf nodes of the Binary Search Tree from the given preorder.Examples : Input : preorder[] = {890, 325, 290, 530, 965};Output : 290 530 965Explanation: Below is the representation of BST using preorder array. Approach:To ide
8 min read
Print all leaf nodes of a binary tree from right to left Given a binary tree, the task is to print all the leaf nodes of the binary tree from right to left. Examples: Input : 1 / \ 2 3 / \ / \ 4 5 6 7 Output : 7 6 5 4 Input : 1 / \ 2 3 / \ \ 4 5 6 / / \ 7 8 9 Output : 9 8 7 4 Recursive Approach: Traverse the tree in Preorder fashion, by first processing t
14 min read
Data Structures and Algorithms | Set 36 Que - 1. The function shiftNode() which takes as input two linked lists- destination and source. It deletes front node from source and places it onto the front of destination. Choose the set of statements which replace X, Y, Z in given function. void shiftNode(struct node** destRoot, struct node** s
4 min read
Remove all leaf nodes from a Generic Tree or N-ary Tree Given an n-ary tree containing positive node values, the task is to delete all the leaf nodes from the tree and print preorder traversal of the tree after performing the deletion.Note: An n-ary tree is a tree where each node can have zero or more children nodes. Unlike a binary tree, which has at mo
6 min read
Print the nodes of binary tree as they become the leaf node Given a binary tree. First print all leaf nodes, after that remove all the leaf nodes from the tree and now print all the new formed leaf nodes and keep doing this until all the nodes are removed from the tree. Examples :Â Input : 8 / \ 3 10 / \ / \ 1 6 14 4 / \ 7 13Output : 4 6 7 13 141 1038Source
10 min read