Untitled

mail@pastecode.io avatar
unknown
plain_text
a year ago
1.7 kB
2
Indexable
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
struct Tree {
	int data;
	struct Tree *left;
	struct Tree *right;
};
Tree *root = NULL;
Tree *createNode(int key){
	Tree *temp;
	temp = new Tree;
	temp->data=key;
	temp->left=temp->right=NULL;
	return temp;
}
Tree *insert(Tree *ptr, int key){
	if(ptr==NULL)
		return createNode(key);
	if(key<ptr->data)
		ptr->left=insert(ptr->left,key);
	else
		ptr->right=insert(ptr->right, key);
	return ptr;
}
void traverse(Tree *ptr){
	if(ptr!=NULL){
		traverse(ptr->left);
		printf("%d ",ptr->data);
		traverse(ptr->right);
	}
}
Tree *minval(Tree *temp){
	Tree *current=temp;
	while(current->left!=NULL)
		current=current->left;
	return current;
}
Tree *deleteNode(Tree *root, int key){
	Tree *temp;
	if(root == NULL) return root;
	if(key<root->data)
		root->left=deleteNode(root->left,key);
	else if(key>root->data)
		root->right=deleteNode(root->right, key);
	else{
		if(root->left==NULL){
			temp=root->right;
			free(root);
			return temp;
		}
		else if(root->right==NULL){
			temp=root->left;
			free(root);
			return temp;
		}
		temp=minval(root->right);
		root->data=temp->data;
		root->right=deleteNode(root->right, temp->data);
	}
	return root;
}
void main(){
	int ch,num;
	clrscr();
	x:
	printf("\n1. Insert\n2. Delete\n3. Traverse\nEnter the choice:");
	scanf("%d", &ch);
	if(ch==1){
		printf("Enter the element: ");
		scanf("%d", &num);
		root=insert(root,num);
		goto x;
	}
	else if(ch==2){
		printf("Enter the element: ");
		scanf("%d", &num);
		root=deleteNode(root, num);
		goto x;
	}
	else if(ch==3){
		traverse(root);
		goto x;
	}
	else
		printf("Wrong entry");
}
















Leave a Comment