Open In App

Restoring BST Structure from Leaf Removal Sequences

Last Updated : 10 Jun, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

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;
}

Output
Output 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.

Next Article

Similar Reads