kaddusingh
kaddusingh

Reputation: 1

Construction of Binary Search Tree from preorder traversal iteratively (not recursion)

The following is the code to converted a preorder traversal of a Binary Search Tree to the original tree.

The following code takes an array of integers, which represent the pre order traversal of a a Binary search tree. The root of the construct tree is returned.

struct Node* constructTree(int pre[], int size)
{
    stack<struct Node* > s;
    int i;
    struct Node* root=newNode(pre[0]);
    struct Node* temp;
    struct Node* top_node;
    s.push(root);
    for(i=1;i<size;i++)
    {
        temp=NULL;
        while(!s.empty()&&pre[i]>(s.top()->data))
            {
                temp=s.top();
                s.pop();
            }
            if(temp==NULL)
            {
                top_node=s.top();
                top_node->left=newNode(pre[i]);
                s.push(top_node->left);
            }else
            {
                temp->right=newNode(pre[i]);
                s.push(temp->right);
            }
    }


    return root;
}

Source: http://www.geeksforgeeks.org/construct-bst-from-given-preorder-traversal-set-2/

I have trouble understanding this code. Can anybody help me understand the following:

  1. At any given iteration, what values are stored in the stack, in relation to the current value being pointed out by pre[i]

  2. Is there any other iterative method for constructing a BST from a given preorder traversal?

Thank you.

Upvotes: 0

Views: 1442

Answers (2)

LearnerOP
LearnerOP

Reputation: 384

Check if this works:

public:
TreeNode* bstFromPreorder(vector<int>& preorder) {
    TreeNode *root = new TreeNode(preorder[0]);
    stack<TreeNode*> nodes;
    nodes.push(root);
    for (int i = 1; i < preorder.size(); i++) {
        TreeNode *temp = new TreeNode(preorder[i]);
        if (temp->val < nodes.top()->val)
            nodes.top()->left = temp;
        else {
            TreeNode *prev;
            while (!nodes.empty() && nodes.top()->val < temp->val) {
                prev = nodes.top();
                nodes.pop();
            }
            prev->right = temp;
        }
        nodes.push(temp);
    }
    return root;
}

Upvotes: 0

David Eisenstat
David Eisenstat

Reputation: 65427

After the iteration where the node containing pre[i] is constructed, the stack contains that node on top, under which its leafmost to rootmost ancestors with exactly one child are stored top to bottom.

Upvotes: 1

Related Questions