Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- #include <string.h>
- struct node{
- int val;
- struct node* next;
- struct node* prev;
- };
- void inorder(struct node* root)
- {
- if (root == NULL)
- return;
- inorder(root->prev);
- printf("%d ",&(root->val));
- inorder(root->next);
- }
- void poorder(struct node* root)
- {
- if (root == NULL)
- return;
- poorder(root->prev);
- poorder(root->next);
- printf("%d ",&(root->val));
- }
- void pop(struct node* stack){
- stack=stack->prev;
- stack->next=NULL;
- }
- void push(struct node* stack, struct node* temp)
- {
- if(stack==NULL){
- stack=temp;
- }else{
- stack->next=temp;
- temp->prev=stack;
- stack=temp;
- }
- };
- // struct node* tree(int* in[], int* po[],int size){
- // return root;
- // }
- int main(){
- int n;
- scanf("%d",&n);
- int in[n],po[n];
- for(int i=0;i<n;i++){
- scanf("%d",&in[i]);
- }
- for(int i=0;i<n;i++){
- scanf("%d",&po[i]);
- }
- // initialized indexes
- int po_index=n-1,in_index=n-1,flag=0;
- // created stack, root and previous
- struct node* stack=(struct node *)malloc(sizeof(struct node));
- struct node* root;
- struct node* previ;
- // pushed first node in stack
- stack->val=(po[po_index]);
- stack->next=NULL;
- stack->prev=NULL;
- --po_index;
- // intitalized root
- root=stack;
- // intitalized prev
- previ=root;
- while(po_index>=0)
- {
- if(stack!=NULL && (in[in_index])==(stack->val)){
- previ=stack;
- pop(stack);
- --in_index;
- flag = 1;
- // no bug till now
- }else{
- // new node created
- struct node* temp=(struct node *)malloc(sizeof(struct node));
- // values assigned to the new node
- temp->val=(po[po_index]);
- temp->next=NULL;
- temp->prev=NULL;
- if(flag==0){
- previ->next = temp;
- previ = temp;
- }else{
- previ->prev= temp;
- previ = temp;
- flag=0;
- }
- push(stack,temp);
- --po_index;
- }
- }
- inorder(root);
- printf("\n");
- poorder(root);
- printf("\n");
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement