2 nodes swap binary tree, Study notes of Data Structures and Algorithms

In this file, programing language code is provided that swap 2 nodes of binary tree

Typology: Study notes

2022/2023

Available from 07/27/2023

Jennifer_0000
Jennifer_0000 🇵🇰

3 documents

1 / 3

Toggle sidebar

This page cannot be seen from the preview

Don't miss anything!

bg1
C language
#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);
pf3

Partial preview of the text

Download 2 nodes swap binary tree and more Study notes Data Structures and Algorithms in PDF only on Docsity!

C language

#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;