

Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
Prepare for your exams
Study with the several resources on Docsity
Earn points to download
Earn points by helping other students or get them with a premium plan
In this file, programing language code is provided that swap 2 nodes of binary tree
Typology: Study notes
1 / 3
This page cannot be seen from the preview
Don't miss anything!


#include <stdio.h> #include <stdlib.h> struct tnode { int data; struct tnode *lchild, *rchild; }; struct tnode *insert(struct tnode *p,int val) { struct tnode temp1,temp2; if(p == NULL) { p = (struct tnode ) malloc(sizeof(struct tnode)); if(p == NULL) { printf("Cannot allocate\n"); exit(0); } p->data = val; p->lchild=p->rchild=NULL; } else { temp1 = p; while(temp1 != NULL) { temp2 = temp1; if( temp1 ->data > val) temp1 = temp1->lchild; else temp1 = temp1->rchild; } if( temp2->data > val) { temp2->lchild = (struct tnode)malloc(sizeof(struct tnode)); temp2 = temp2->lchild; if(temp2 == NULL) { printf("Cannot allocate\n"); exit(0);
temp2->data = val; temp2->lchild=temp2->rchild = NULL; } else { temp2->rchild = (struct tnode*)malloc(sizeof(struct tnode)); temp2 = temp2->rchild; if(temp2 == NULL) { printf("Cannot allocate\n"); exit(0); } temp2->data = val; temp2->lchild=temp2->rchild = NULL; } } return(p); } void inorder(struct tnode *p) { if(p != NULL) { inorder(p->rchild); printf("%d\t",p->data); inorder(p->lchild); } } struct tnode *swaptree(struct tnode *p) { struct tnode *temp1=NULL, *temp2=NULL; if( p != NULL) { temp1= swaptree(p->lchild); temp2 = swaptree(p->rchild); p->rchild = temp1; p->lchild = temp2; } return(p); } void main() { struct tnode *root = NULL;