preorder to postorder gfg practice code example
Example: preorder to postorder gfg practice
Node* constructTree(int pre[], int n)
{
Node* root= newNode(pre[0]);
Node* temp=root;
stack<Node*>st;
st.push(root);
int i=0;
while(i<n)
{
if(st.top()->data>pre[i])
{
temp=st.top();
temp->left= newNode(pre[i]);
st.push(temp->left);
//temp=temp->left;
}
Node* curr=NULL;
while(!st.empty()&&(st.top()->data<pre[i]))
{
curr=st.top();
st.pop();
}
if(curr)
{
curr->right=newNode(pre[i]);
st.push(curr->right);
}
i++;
}
return root;
}