I have written a code to create an AVL tree.
Write a program that sorts the given integer values. The number of values is not known in advance. Your program will output the sorted values and the structure of the tree using given output format. (Assume for this lab study,
values are distinct). Use AVL tree in your program.
Input:
72 18 28 36 27 117 108 90 -1
Your output will be the sorted list of given numbers (In-order walk on AVL tree produce the sorted list).
18
27
28
36
72
90
108
117
Your program should also print the AVL tree in the following way (First number represents the value, second number displays the parent node and the third number shows the balance factor. B is used for balance factor, L represents left child and R represents right child).
28 (-1 B)
18 (28 L) (-1 B) 72 (28 R) (-1 B)
27 (18 R) (0 B) 36 (72 L) (0 B) 108 (72 R) (0 B) 90 (108 L) (0 B) 117 (108 R) (0 B)
#include <stdio.h>
#include <stdlib.h>
struct treeNode {
int value;
struct treeNode* leftChild;
struct treeNode* rightChild;
int height;
};
int height( struct treeNode *root) {
if(root==NULL) {
return -1;
}
else {
return root->height;
}
}
int max(int a,int b) {
if (a>b) {
return a;
}
else {
return b;
}
}
struct treeNode *createNode( int value) {
struct treeNode* root= (struct treeNode*) malloc(sizeof(struct treeNode));
root->value=value;
root->leftChild=NULL;
root->rightChild=NULL;
root->height=1;
return root;
}
int balanceFactor(struct treeNode *root) {
if(root==NULL) {
return 0;
}
else {
return height(root->leftChild)-height(root->rightChild);
}
}
struct treeNode *leftRotation(struct treeNode* parent) {
struct treeNode *child1= parent->rightChild;
struct treeNode *child2= child1->leftChild;
child1->leftChild=parent;
parent->rightChild= child2;
parent->height=max(height(parent->rightChild), height(parent->leftChild)) +1;
child1->height=max(height(child1->rightChild), height(child1->leftChild)) +1;
return child1;
}
struct treeNode *rightRotation(struct treeNode* child1) {
struct treeNode *parent = child1->rightChild;
struct treeNode *child2= parent->rightChild;
parent->rightChild=child1;
child1->leftChild= child2;
parent->height=max(height(parent->rightChild), height(parent->leftChild)) +1;
child1->height=max(height(child1->rightChild), height(child1->leftChild)) +1;
return parent;
}
struct treeNode *RL(struct treeNode *c) {
c->leftChild=rightRotation(c->leftChild);
return leftRotation(c);
}
struct treeNode *LR(struct treeNode *b) {
b->rightChild=leftRotation(b->rightChild);
return rightRotation(b);
}
struct treeNode *insert(struct treeNode* root, int value) {
if (root==NULL) {
return (createNode(value));
}
if( value< root->value) {
root->leftChild= insert(root->leftChild,value);
}
else if(value> root->value) {
root->rightChild=insert(root->rightChild, value);
}
else {
return root;
}
root->height=1 + max(height(root->leftChild), height(root->rightChild));
int balanceF= balanceFactor(root);
if(balanceF<-1 && value> root->rightChild->value) {
return leftRotation(root);
}
if (balanceF<-1 && value< root->rightChild->value) {
root->rightChild=rightRotation(root->rightChild);
return leftRotation(root);
}
if(balanceF>1 && value<root->leftChild->value) {
return rightRotation(root);
}
if(balanceF>1 && value<root->leftChild->value) {
root->leftChild=leftRotation(root->leftChild);
return rightRotation(root);
}
return root;
}
void inorder(struct treeNode *root) {
if (root) {
inorder(root->leftChild);
printf("%d \n", root->value);
inorder(root->rightChild);
}
}
int treeHeight( struct treeNode *root) {
if (root== NULL ) {
return 0;
}
else{
int leftHeight = treeHeight(root->leftChild);
int rightHeight= treeHeight(root->rightChild);
if (leftHeight>rightHeight) {
return (leftHeight+1);
}
else {
return (rightHeight+1);
}
}
}
void currentLevel (struct treeNode *root, int treeheight, struct treeNode *parent, char child ) {
if (root != NULL) {
if (treeheight==0) {
if (parent !=NULL) {
int bf=balanceFactor(root);
printf("%d (%d %c)(%d B)", root->value, parent->value, child, bf);
}
else {
printf("%d \n", root->value);
}
}
else if (treeheight>0) {
currentLevel(root->leftChild, treeheight-1, root, 'L' );
currentLevel(root->rightChild, treeheight-1, root, 'R');
}
}
}
int main () {
struct treeNode *root = NULL;
int value;
while(1) {
scanf ("%d", &value);
if(value==-1) {
break;
}
root=insert(root,value);
}
inorder(root);
int i;
int height= treeHeight(root);
for (int i=0; i<=height;i++) {
currentLevel(root,i, NULL, ' ');
printf("\n");
}
return 0;
}
Related
if i input 15,7,22,3 into this AVL tree, and then i delete 22, the tree then displays only 15. what happened to 7 and 3?? also when i enter the data in this particular order -> 15,7,3,22 and then i delete 22, the program then seems to work fine, i get 15,7 and 3 as my output which is fully balanced. this is very strange. please help me out.
#include <stdio.h>
#include <stdlib.h>
struct node
{
int data;
struct node *left;
struct node *right;
int height;
};
struct node *tree=NULL;
int height(struct node *tree)
{
if(tree==NULL)
return -1;
else{
int lh=height(tree->left);
int rh=height(tree->right);
if(lh>rh)
return 1+lh;
else
return 1+rh;
}
}
int max(int a,int b)
{
return ((a < b)?b:a);
}
int getbalance(struct node *tree)
{
if(tree==NULL)
return 0;
return (height(tree->left)-height(tree->right));
}
struct node *rr(struct node *y)
{
struct node *x,*t2;
x=y->left;
t2=x->right;
x->right=y;
y->left=t2;
return x;
};
struct node *ll(struct node *x)
{
struct node *y,*t2;
y=x->right;
t2=x->left;
y->left=x;
x->right=t2;
return y;
};
struct node *newNode(int val)
{
struct node *ptr;
ptr=(struct node *)malloc(sizeof(struct node));
ptr->data=val;
ptr->left=ptr->right=NULL;
ptr->height=1;
return ptr;
};
struct node *create(struct node *tree,int val)
{
if(tree==NULL)
return newNode(val);
else if(val < tree->data)
tree->left=create(tree->left,val);
else if(val > tree->data)
tree->right=create(tree->right,val);
else
{
printf("\n duplicate value ignored");
return tree;
}
tree->height=1+max(height(tree->left),height(tree->right));
int balance=getbalance(tree);
if(balance>1 && val<tree->left->data)
return rr(tree);
else if(balance<-1 && val>tree->right->data)
return ll(tree);
else if(balance>1 && val>tree->left->data)
{
tree->left=ll(tree->left);
return rr(tree);
}
else if(balance<-1 && val<tree->right->data)
{
tree->right=rr(tree->right);
return ll(tree);
}
return tree;
};
struct node *inordersuccesor(struct node *tree)
{
struct node *ptr;
ptr=tree;
while(ptr->left!=NULL)
{
ptr=ptr->left;
}
return ptr;
}
struct node *delnode(struct node *tree,int val)
{
if(tree==NULL)
return 0;
else if(val<tree->data)
tree->left=delnode(tree->left,val);
else if(val>tree->data)
tree->right=delnode(tree->right,val);
else
{
struct node *temp;
if(tree->left==NULL)
{
temp=tree->right;
free(tree);
return temp;
}
else if(tree->right==NULL)
{
temp=tree->left;
free(tree);
return temp;
}
else
{
temp=inordersuccesor(tree->right);
tree->data=temp->data;
tree->right=delnode(tree->right,temp->data);
}
}
int balance=getbalance(tree);
if(balance==2 && getbalance(tree->left)>=0)
return rr(tree);
else if(balance==2 && getbalance(tree->left)==-1)
{
tree->left=ll(tree->left);
return rr(tree);
}
else if(balance==-2 && getbalance(tree->right)<=-0)
return ll(tree);
else if(balance==-2 && getbalance(tree->right)==1)
{
tree->right=rr(tree->right);
return ll(tree);
}
return tree;
};
void display(struct node *tree)
{
if(tree!=NULL)
{
display(tree->left);
printf("\t%d",tree->data);
display(tree->right);
}
}
int main()
{
int val,option;
do{
printf("\n 1. create");
printf("\n 2. display");
printf("\n 3. find height");
printf("\n 4. balance factor");
printf("\n 5. delete node");
printf("\n 6. exit\n");
scanf("%d",&option);
switch(option)
{
case 1: printf("\n enter val: ");
scanf("%d",&val);
tree=create(tree,val);
break;
case 2: display(tree);
break;
case 3:
printf("\n height [%d]\n",height(tree));
break;
case 4:
printf("\n balance factor = [%d]",getbalance(tree));
break;
case 5:
printf("\n delete node: ");
scanf("%d",&val);
delnode(tree,val);
break;
}
}while(option!=6);
}
I built three files, which includes MainFunc.c, AllFun.h, and OtheFunc.c.
The program happens runtime error, which print nothing. However, I need it output a tree as previous order.
I guess the problem may be that I built an empty tree, but I can't solve it.
MainFunc.c
#include "AllFun.h"
int main(int argc, char* argv[])
{
int nums[MaxSize] = { 0 };
printf("Enter value of root node: ");
for (int i = 0; i < MaxSize; ++i) {
scanf_s("%d", &nums[i]);
}
TreeNode* root = create(nums, MaxSize);
preorder(root);
return 0;
}
AllFun.h
#include <stddef.h> // NULL
#include <stdlib.h>
#include <stdio.h>
#define MaxSize 10
typedef struct node {
int data;
struct node* lchild, * rchild;
} TreeNode;
TreeNode *create(int nums[], int n);
void preorder(TreeNode *root);
OtheFunc.c
#include "AllFun.h"
TreeNode* newNode(int v) {
TreeNode* node = (TreeNode*)malloc(sizeof(TreeNode));
if (node) {
node->data = v;
node->lchild = node->rchild = NULL;
return node;
}
}
void insert(TreeNode* root, int x)
{
if (root == NULL) {
root = newNode(x);
return;
}
if (root->data < x) {
insert(root->lchild, x);
}
else {
insert(root->rchild, x);
}
}
TreeNode *create(int nums[], int n)
{
TreeNode* root = NULL; // Build a empty root node
for (int i = 0; i < n; i++) {
insert(root, nums[i]);
}
return root;
}
void preorder(TreeNode* root)
{
if (root == NULL) {
return;
}
printf("%d ", root->data);
preorder(root->lchild);
preorder(root->rchild);
}
You have to pass the node as a pointer to pointer, then the function can change the pointer:
void insert(TreeNode** root, int x)
{
if (*root == NULL) {
*root = newNode(x);
return;
}
if ((*root)->data < x) {
insert(&(*root)->lchild, x);
}
else {
insert(&(*root)->rchild, x);
}
}
Call with insert(&root, nums[i]);:
https://ideone.com/nV5q1g
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct listNode {
int id;
struct listNode *next;
} ListNode;
typedef struct treeNode {
char *word;
char *key;
int freq;
ListNode *head;
struct treeNode *left;
struct treeNode *right;
} TreeNode;
TreeNode *insertItem(TreeNode *root, char *gword);
void printTreeInorder(TreeNode *v);
void searchforexist(TreeNode *root, char *key);
int searchItem(TreeNode *root, char *word);
void Heap(TreeNode *arr[],TreeNode *root, int i);
void maxheap(TreeNode *arr[],int k);
void freeNodes(TreeNode *root);
#define MAX 25
int main() {
char in[MAX];
char word[MAX];
TreeNode *root = NULL;
int comp;
int f=0;
int t=0;
FILE *fp = fopen("input.txt", "r");
memset(word, 0, MAX);
if (fp != NULL) {
while (fscanf(fp, "%24s \n", word) != EOF) {
root = insertItem(root, word);//insert items
t++;
if (strcmp(word, "eof") == 0) break;
}
fclose(fp);
}
// User inputs word
printf("Give word");
printf("\n");
scanf("%s",in);
comp=strcmp(in,"#");
while(comp!=0)
{
printf("Give word");
printf("\n");
scanf("%s",in);
comp=strcmp(in,"#");
if(comp==1)
break;
f=searchItem(root,in);
printf("%d",f);
f=0;
printf("\n");
}
TreeNode *arr[t];
Heap(arr,root,t);// HEAPPPPPPPPPPPPPPPPPPPPPPPPPPPP
printTreeInorder(root);
printf("\n");
freeNodes(root);
return 0;
}
TreeNode *insertItem(TreeNode *root, char *gword) {
TreeNode *v = root;
TreeNode *pv = NULL;
while (v != NULL) {
pv = v;
int comp = strcmp(gword, v->word);
if (comp < 0) {
v = v->left;
} else if (comp > 0) {
v = v->right;
} else {
char *word = v->word;
searchforexist(root,v->word);
return root;
}
}
TreeNode *tmp = (TreeNode *)malloc(sizeof(TreeNode));
tmp->word = strdup(gword);
tmp->left = tmp->right = NULL;
tmp->freq = 1;
if (root != NULL) {
if (strcmp(gword, pv->word) < 0) {
pv->left = tmp;
} else {
pv->right = tmp;
}
} else
root = tmp;
return root;
}
void searchforexist(TreeNode *root, char *word) {
if(root == NULL) {
return;
}
int comp = strcmp(word, root->word);
if(comp == 0) {
root->freq++;
} else {
searchforexist(comp < 0 ? root->left : root->right , word);
}
}
int searchItem(TreeNode *root, char *word)
{
if(root == NULL) {
return 0;
}
int comp = strcmp(word, root->word);
if(comp == 0) {
return root->freq;
} else {
searchItem(comp < 0 ? root->left : root->right , word);
}
}
void Heap(TreeNode *arr[],TreeNode *root, int i)
{
int k=0;
while(k<i)
{
if(root==NULL){
maxheap(arr,k);
}
arr[k]=root;
k++;
if (k=i){
maxheap(arr,k);
break;
}
Heap(arr,root->left,k);
Heap(arr,root->right,k);
}
}
void maxheap(TreeNode *arr[],int k)
{
int i;
int j;
for (i = 0; i < k; i++)
{
for (j = 0; j < k; j++)
{
if(arr[i]->freq>arr[j]->freq)
{
TreeNode *tmp = arr[i];
arr[i] = arr[j];
arr[j] = tmp;
}
}
}
for (i = 0; i < k; i++)
{
printf("%s %d",arr[i]->word,arr[i]->freq);
}
}
void printTreeInorder(TreeNode *v)
{
if (v==NULL) return;
printf("(");
printTreeInorder(v->left);
printf(")");
printf(" %.4s ", v->word);
printf("(");
printTreeInorder(v->right);
printf(")");
}
void freeNodes(TreeNode *root) {
if (root == NULL) {
return;
}
freeNodes(root->left);
freeNodes(root->right);
if(root->word != NULL) free(root->word);
if(root->key != NULL) free(root->key);
free(root);
return;
}
This program reads a file and puts all strings to a binary search tree. Repeating words are not added but the frequency counter increases (searchforexist). Then the user types a word and the program displays the frequency of the word typed.
The above works fine using any input file.
However im having trouble with the next steps of the assignment:
After that the hole tree is suppose to be copied in a maxheap based on the frequency of each word. The heap must be created using array with size equal to the elements of a tree. Every cell of said array must contain a pointer that points to a node in the binary search tree so we can still access the word inside and its frequency.
The user then inputs an int number and the programm prints all words that have frequency less that the number inputed by the user.
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct listNode {
int id;
struct listNode *next;
} ListNode;
typedef struct treeNode {
char *word;
char *key;
int freq;
ListNode *head;
struct treeNode *left;
struct treeNode *right;
} TreeNode;
TreeNode *insertItem(TreeNode *root, char *gword);
void printTreeInorder(TreeNode *v);
void searchforexist(TreeNode *root, char *key);
int searchItem(TreeNode *root, char *word);
void freeNodes(TreeNode *root);
#define MAX 25
int main() {
char in[MAX];
char word[MAX];
TreeNode *root = NULL;
int comp;
int f=0;
FILE *fp = fopen("input.txt", "r");
memset(word, 0, MAX);
if (fp != NULL) {
while (fscanf(fp, "%24s \n", word) != EOF) {
root = insertItem(root, word);//insert items
if (strcmp(word, "eof") == 0) break;
}
fclose(fp);
}
// User inputs word
printf("Give word");
printf("\n");
scanf("%s",in);
comp=strcmp(in,"#");
while(comp!=0)
{
printf("Give word");
printf("\n");
scanf("%s",in);
comp=strcmp(in,"#");
if(comp==1)
break;
f=searchItem(root,in);
printf("%d",f);
f=0;
printf("\n");
}
//heapcreating here
printTreeInorder(root);
printf("\n");
freeNodes(root);
return 0;
}
TreeNode *insertItem(TreeNode *root, char *gword) {
TreeNode *v = root;
TreeNode *pv = NULL;
while (v != NULL) {
pv = v;
int comp = strcmp(gword, v->word);
if (comp < 0) {
v = v->left;
} else if (comp > 0) {
v = v->right;
} else {
char *word = v->word;
searchforexist(root,v->word);
return root;
}
}
TreeNode *tmp = (TreeNode *)malloc(sizeof(TreeNode));
tmp->word = strdup(gword);
tmp->left = tmp->right = NULL;
tmp->freq = 1;
if (root != NULL) {
if (strcmp(gword, pv->word) < 0) {
pv->left = tmp;
} else {
pv->right = tmp;
}
} else
root = tmp;
return root;
}
void searchforexist(TreeNode *root, char *word) {
if(root == NULL) {
return;
}
int comp = strcmp(word, root->word);
if(comp == 0) {
root->freq++;
} else {
searchforexist(comp < 0 ? root->left : root->right , word);
}
}
int searchItem(TreeNode *root, char *word)
{
if(root == NULL) {
return 0;
}
int comp = strcmp(word, root->word);
if(comp == 0) {
return root->freq;
} else {
searchItem(comp < 0 ? root->left : root->right , word);
}
}
void printTreeInorder(TreeNode *v)
{
if (v==NULL) return;
printf("(");
printTreeInorder(v->left);
printf(")");
printf(" %.4s ", v->word);
printf("(");
printTreeInorder(v->right);
printf(")");
}
void freeNodes(TreeNode *root) {
if (root == NULL) {
return;
}
freeNodes(root->left);
freeNodes(root->right);
if(root->word != NULL) free(root->word);
if(root->key != NULL) free(root->key);
free(root);
return;
}
I and many of us make simple mistakes. Use the automated tools you have to increase your coding efficiency.
Save time, enable all compiler warnings - or use a better compiler.
warning: control reaches end of non-void function [-Wreturn-type]
searchItem() needs to return a value.
int searchItem(TreeNode *root, char *word) {
if (root == NULL) {
return 0;
}
int comp = strcmp(word, root->word);
if (comp == 0) {
return root->freq;
} else {
// searchItem(comp < 0 ? root->left : root->right, word);
return searchItem(comp < 0 ? root->left : root->right, word);
}
}
Other problems may exist.
i have to create binary search tree. so i have used nested structure. i am not able to maintain head of the tree. when i give inputs then it is creating new node of every input. Help me with how to handle Head.
tree.h
#ifndef __TREE__H__
#define __TREE__H__
typedef struct _BSTNode
{
int data;
struct _BSTNode *left,*right;
}BSTNode;
typedef struct _BST
{
BSTNode *tHead;
}BST;
int insertBST(BST ,int);
#endif
mainTree.c
#include"tree.h"
#include<stdio.h>
int main()
{
FILE *fp;
BST bst;
bst.tHead=NULL;
int element;
fp = fopen("input","r");
while(fscanf(fp,"%d",&element)!=EOF)
{
insertBST(bst,element);
}
return 0;
}
insertBST.c
#include"tree.h"
#include<stdio.h>
int insertBST(BST bst,int element)
{
return _insertBST(bst.tHead,NULL,element);
}
int _insertBST(BSTNode *p,BSTNode *parent,int e)
{
if(p==NULL)
return createBST(p,e);
if(p->data == e)
return 0;
if(p->data < e)
return _insertBST(p->right,p,e);
if(p->data > e)
return _insertBST(p->left,p,e);
return -1;
}
createBST.c
#include"tree.h"
#include<stdlib.h>
#include<stdio.h>
int createBST(BSTNode *p,int element)
{
BSTNode *node = (BSTNode *)malloc(sizeof(BSTNode));
node->data = element;
node->left = NULL;
node->right = NULL;
if(p== NULL)
{
p=node;
fprintf(stdout,"Im here 1");
return 0;
}
else
{
if(p->data < node ->data)
(p->left) = node;
fprintf(stdout,"Im here 2");
return 0;
if(p->data > node ->data)
(p->right) = node;
fprintf(stdout,"Im here 3");
return 0;
}
}
output:-
#:~/Ds/tree$gcc mainTree.c insertBST.c createBST.c
#:~/Ds/tree$ ./a.out
Im here 1Im here 1Im here 1Im here 1Im here 1
input :- 40 10 30 20
I want to write a BST,but the insert function doesn't work. Debugging it , I found that it was not inserting.
/* Binary Search Tree (BST).demo */
#include <stdio.h>
#include <stdlib.h>
typedef struct treeNode{
int data;
struct treeNode* lChild;
struct treeNode* rChild;
} treeNode;
treeNode* createNode(){
treeNode *nNode;
nNode=(struct treeNode*)malloc(sizeof(treeNode));
nNode->data=0;
nNode->lChild=NULL;
nNode->rChild=NULL;
return nNode;
}
void insert(treeNode* rt,int idata)
{
if(rt==NULL){
treeNode* nNode;
nNode=createNode();
nNode->data=idata;
rt=nNode;
rt->lChild=NULL;
rt->rChild=NULL;
}else{
if(idata < rt->data)
insert(rt->lChild,idata);
else insert(rt->rChild,idata);
}
}
int main()
{
treeNode *root;
root=(treeNode*)malloc(sizeof(treeNode));
root->data=15;
root->lChild=NULL;
root->rChild=NULL;
insert(root,13);
if(root->lChild==NULL)
printf("root no l child\n");
// printf("root lchild data :%d",root->lChild->data);
return 0;
}
use this as the insert function :
void insert(treeNode** rt,int idata)
{
if((*rt)==NULL)
{
treeNode* nNode;
nNode=createNode();
nNode->data=idata;
*rt=nNode;
(*rt)->lChild=NULL;
(*rt)->rChild=NULL;
}
else
{
if(idata < (*rt)->data)
insert(&((*rt)->lChild),idata);
else
insert(&((*rt)->rChild),idata);
}
}
and the insert function call in main() as:
insert(&root,13);
I usually implement it like this:
void insert(treeNode* rt, int idata) {
// assert( rt != NULL );
if(idata < rt->data){
if( rt->lChild != NULL)
insert(rt->lChild, idata);
else {
rt->lChild = createNode();
rt->lChild->data = idata;
}
} else {
if( rt->rChild != NULL)
insert(rt->rChild, idata);
else {
rt->rChild = createNode();
rt->rChild->data = idata;
}
}
}
Moreover, I prefer give an argument to createNode()
treeNode* createNode(int idata){
// ...
nNode->data = idata;
// ...
}
So the insert will look like:
void insert(treeNode* rt, int idata) {
// ...
rt->lChild = createNode(idata);
// ...
rt->rChild = createNode(idata);
// ...
}