15,311,717 members
See more:
My AVL tree cannot do balancing. i don't know how to fix this since i'm still new in programming.

What I have tried:

C
```
```

```#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define COUNT 10

struct DictNode {
char word[128], meaning[256];
struct DictNode *left, *right;
int height;
};

char temp_w[128];
char temp_m[256];

//get maximum of two integers
int max(int l, int r);
// Get Height of tree
int height(struct DictNode *n){
if (n == NULL)
return 0;
return n->height;
}

int max(int l, int r){
if(l>r)return l;
return r;
}

//Get balance factor of node
int getBalanceFactor(struct DictNode *n){
if(n==NULL){
return 0;
}
return height(n->left) - height(n->right);
}

//leftleft rotate
struct DictNode *singlerightrotate(struct DictNode *y){
struct DictNode *x = y->left;
struct DictNode *T2 = x->right;

/*            y
/
x
/ \
z   T2
*/

//Perform rotation
y->left = x->right;
x->right = y;
y->left = T2;

// Update heights
y->height = max(height(y->left), height(y->right))+1;
x->height = max(height(x->left), height(x->right))+1;

/*
x
/ \
z   y
/
T2
*/
return x;//x is root
}

//right right rotate
struct DictNode *singleleftrotate(struct DictNode *x){

struct DictNode *y = x->right;
struct DictNode *T2 = y->left;

/* Before rotate
x
\
y
/ \
T2   z
*/

//Perform rotation
x->right=y->left;
y->left = x;
x->right = T2;

// Update heights
x->height = max(height(x->left), height(x->right))+1;
y->height = max(height(y->left), height(y->right))+1;

/*After rotate
y
/  \
x    z
\
T2
*/
return y;//y is root
}
//leftright rotate
struct DictNode *doublerightrotate(struct DictNode *z){
z->left = singleleftrotate(z->left);
return singlerightrotate(z);
}
//rightleft rotate
struct DictNode *doubleleftrotate(struct DictNode *x){
x->right = singlerightrotate(x->right);
return singleleftrotate(x);
}

//new node with the given key and NULL left and right pointers
//structure variable declaration
struct DictNode * createNode(char *word, char *meaning){
struct DictNode *newnode = (struct DictNode *)malloc(sizeof(struct DictNode));
strcpy(newnode->word,word);
strcpy(newnode->meaning,meaning);
newnode->left = newnode->right = NULL;
newnode->height = 1;  // new node is initially added at leaf
return newnode;
}

void *insert(struct DictNode*root,char *word, char *meaning){

//1.perform the normal BST insertion

struct DictNode*prev = NULL;
if (root==NULL) {
struct DictNode *newnode = createNode(word, meaning);
return;
}
while(root!=NULL){
prev=root;
if(strcmp(root->word,word)==0){
return;
}
else if(strcmp(root->word,word)>0){
root=root->left;
}
else{
root=root->right;
}
}
struct DictNode *newnode = createNode(word,meaning);
if(strcmp(prev->word,word)>0){
prev->left=newnode;
}
else {
prev->right=newnode;
}
//2.Update height of this ancestor node
root->height = 1 + max(height(root->left),height(root->right));
int bf = getBalanceFactor(root);

// Left Left Case
if (bf > 1 && getBalanceFactor(root->left)>0){
return singlerightrotate(root);
}

// Right Right Case
else if (bf < -1 && getBalanceFactor(root->right)<=0){
return singleleftrotate(root);
}

// Left Right Case
else if (bf > 1 && getBalanceFactor(root->left)<=0){
return doublerightrotate(root);
}

// Right Left Case
else if (bf < -1 && getBalanceFactor(root->right)>0){
return doubleleftrotate(root);
}
return root;
}

//successor right subtree left most
struct DictNode *successor(struct DictNode*root){
while (root->left != NULL)
root = root->left;

return root;
}
void * delete(struct DictNode *root,char *word) {
if(root=NULL){
return root;
}
if (strcmp(root->word,word)>0){
root->left=delete(root->left,word);
}
else if (strcmp(root->word,word)<0){
root->right=delete(root->right,word);
}
else{
if(root->left==NULL){
struct DictNode*temp=root->right;
free(root);
return temp;
}
else if(root->right==NULL){
struct DictNode*temp=root->right;
free(root);
return temp;
}
else if(root->left&&root->right==NULL){//no child case
struct DictNode*temp=root;
root=NULL;
free(root);
}
else
{
struct DictNode*succ=successor(root->right);
strcpy(root->word,succ->word);//copy successor node to root node
root->right=delete(root->right,succ->word);
}
}

//2.Update height this ancestor
root->height = max(height(root->left),height(root->right))+1;

//3.Get balance factor this ancestor
int bf = getBalanceFactor(root);

//Left left case
//bf of root>1 && bf root left>=0
if(bf == 2 && getBalanceFactor(root -> left) >= 0)
return singlerightrotate(root);

//Right right case
if(bf == -2 && getBalanceFactor(root -> right) <= -0)
return singleleftrotate(root);

//Left right case
if(bf == 2 && getBalanceFactor(root -> left) == -1){
return doublerightrotate(root);
}

//Right left case
if(bf == -2 && getBalanceFactor(root -> right) == 1){
return doubleleftrotate(root);
}

return root;
}

void search(struct DictNode *root,char *str) {
struct DictNode *temp = NULL;
int flag = 0, res = 0;
if (root == NULL) {//empty tree
printf("Binary Search Tree is out of station!!\n");
return;
}
temp = root;//value of root assign temporary
while (temp) {
if ((res = strcasecmp(temp->word, str)) == 0) {
printf("Word   : %s", str);
printf("Meaning: %s", temp->meaning);
flag = 1;//data is exists
break;
}
temp = (res > 0) ? temp->left : temp->right;
}
if (!flag)//flag==0 data not exists
return;
}

void view(struct DictNode *myNode) {
if (myNode) {
view(myNode->left);
printf("Word    : %s", myNode->word);
printf("Meaning : %s", myNode->meaning);
printf("\n");
view(myNode->right);
}
return;
}

/* Function to do preorder traversal of tree */
void preOrder(struct DictNode *root)
{
if(root != NULL)
{
printf("%s", root->word);
preOrder(root->left);
preOrder(root->right);
}
return;
}

void print2DUtil(struct DictNode *root, int space)
{
if (root == NULL)
return;

// Increase distance between levels
space += COUNT;

// Process left child first
print2DUtil(root->right, space);

// Print current node after space
// count
printf("\n");
for (int i = COUNT; i < space; i++)
printf(" ");
printf("%s\n", root->word);

// Process right child
print2DUtil(root->left, space);
}

// Wrapper over print2DUtil()
void print2D(struct DictNode *root)
{
// Pass initial space count as 0
print2DUtil(root,0);
}

int main() {

printf("\n.....WELCOME TO DICTIONARY.....\n");
printf("\n1. Insertion\t2. Deletion\n");
printf("3. Searching\t4. View\n");
printf("5. Traversal\t6.2D print\n");
printf("7. Quit\n");

int choice;
scanf("%d",&choice);
if(choice==1){
printf("Enter word:\n");
while((getchar()!='\n'));
scanf("%[^\n]%*c",temp_w);

printf("Enter meaning:\n");
scanf("%[^\n]%*c",temp_m);
}
else if(choice==2){
printf("Enter word to delete:\n");
while((getchar()!='\n'));
scanf("%[^\n]%*c",temp_w);
}
else if(choice==3){
if(root==NULL){
printf("Word is not exist\n");
}
printf("Enter word:\n");
scanf("%[^\n]%*c",temp_w);
search(root,temp_w);
}
else if(choice==4){
view(root);
}
else if(choice==5){
preOrder(root);

}
else if(choice==6){
}
else if(choice==7){
exit(0);
}
return 0;
}```
Posted
Updated 7-Dec-21 20:27pm

## Solution 1

Compiling does not mean your code is right! :laugh:
Think of the development process as writing an email: compiling successfully means that you wrote the email in the right language - English, rather than German for example - not that the email contained the message you wanted to send.

So now you enter the second stage of development (in reality it's the fourth or fifth, but you'll come to the earlier stages later): Testing and Debugging.

Start by looking at what it does do, and how that differs from what you wanted. This is important, because it give you information as to why it's doing it. For example, if a program is intended to let the user enter a number and it doubles it and prints the answer, then if the input / output was like this:
```Input   Expected output    Actual output
1            2                 1
2            4                 4
3            6                 9
4            8                16```
Then it's fairly obvious that the problem is with the bit which doubles it - it's not adding itself to itself, or multiplying it by 2, it's multiplying it by itself and returning the square of the input.
So with that, you can look at the code and it's obvious that it's somewhere here:
C
```int Double(int value)
{
return value * value;
}```

Once you have an idea what might be going wrong, start using the debugger to find out why. Put a breakpoint on the first line of the method, and run your app. When it reaches the breakpoint, the debugger will stop, and hand control over to you. You can now run your code line-by-line (called "single stepping") and look at (or even change) variable contents as necessary (heck, you can even change the code and try again if you need to).
Think about what each line in the code should do before you execute it, and compare that to what it actually did when you use the "Step over" button to execute each line in turn. Did it do what you expect? If so, move on to the next line.
If not, why not? How does it differ?
Hopefully, that should help you locate which part of that code has a problem, and what the problem is.
This is a skill, and it's one which is well worth developing as it helps you in the real world as well as in development. And like all skills, it only improves by use!