Given an array pre[] of N nodes representing preorder traversal of BST. The task is to print its postorder traversal
belongs to collection: Interview C++ coding problems/challenges | String
All Answers
total answers (1)
belongs to collection: Interview C++ coding problems/challenges | String
total answers (1)
Pseudo Code:
//postorder function to print data in postorder manner. void postorder(Node* root) { //if root==NULL then simply return if (root == NULL) return; else { postorder(root->left); //recursively call for left child postorder(root->right); //recursively call for right child cout << root->data << " "; //print the current data } return; } //function to construct binary search tree //from preorder traversal. void insert(ll data) { Node* newnode = new Node(data); //if root is NULL then create new node and assign it to root. if (root == NULL) { root = newnode; return; } else { Node* temp = root; while (1) { //if data is smaller than root element then it must in left //part of the BST so check for left side. if (temp->data > data) { //if left child of root is NULL then simply assign new node //to left part else left is assigned to //left child and then we check again and again //until we get correct structure. if (temp->left == NULL) { temp->left = newnode; break; } else temp = temp->left; } else { //if data is greater than equal to root element then //it must in right part of the BST so check for right side. //if right child of root is NULL then simply assign new node //to right part else right is assigned to //right child and then we check again and again until //we get correct structure. if (temp->right == NULL) { temp->right = newnode; break; } else temp = temp->right; } } } } // solve function which will return the BST tree and print it // postorder form after calling insert and postorder function. void solve(int pre[],int n) { // add the elements to BST for(int i=0;i<n;i++) insert(pre[i]); // print its postorder form. postorder(root); }C++ Implementation:
Output
need an explanation for this answer? contact us directly to get an explanation for this answer