I was working on a class assignment today and I wrote this code which works perfectly fine. It looks tho kind of has too much 'if statements' in it, and I was thinking that it could be written much better than this. (I'm still a beginner in C).
Do you suggest any new techniques that I could use/learn to avoid so many if
statements and how could you improve this code without making it much longer or complex?
The code is a part of much bigger code to add a new node in an AVL tree.
if (avlt->root == NULL) {
new = &(avlt->root);
parent = NULL;
}
if (avlt->root != NULL) {
parent = avlt->root;
while (1)
{
if (parent->value > value)
{
if (parent->left) parent = parent->left;
else
{
new = &(parent->left);
break;
}
}
else if (parent->value < value)
{
if (parent->right) parent = parent->right;
else
{
new = &(parent->right);
break;
}
}
else return;
}
}
These are the structs, maybe they can be useful for you to understand the code:
struct AVLNode {
struct AVLNode* left;
struct AVLNode* right;
struct AVLNode* parent;
int value;
int height;
};
struct AVLTree {
struct AVLNode* root;
int numberOfNodes;
};
typedef struct AVLNode AVLNode;
typedef struct AVLTree AVLTree;