I'm trying to insert into a complete binary tree for a school assignment. The structure of my tree is as such
typedef struct TreeNode {
void * data;
struct TreeNode * left;
struct TreeNode * right;
struct TreeNode * parent;
} TNode;
typedef struct CompleteBinaryTree {
TNode * root;
TNode * last;
int numelm;
} CBTree;
I have 4 ways of inserting depending the situation
- The tree is empty
- The tree as one node
- The last node of the CBT is his parent left child
- Finally I go up the tree as long as the current node is the right node of his parent, if the current node is not the root I will go to his brother and go down left, else I just go down left
I'm currently stuck on my third way and I don't know what is wrong with my code.
Could somebody push me in the right direction.
Thank you !
void CBTreeInsert(CBTree* tree, void* data) {
TNode * tmp = newTNode(data);
TNode * curr = tree->last;
if(tree->root == NULL) //empty
{
tree->root = tmp;
}
else if(tree->last == tree->root) //one node
{
tree->last->left = tmp;
}
else if(tree->last->parent->right == NULL) //general
{
tree->last->parent->right = tmp;
}
else if(tree->last->parent == tree->last->parent->right) //degenarated
{
while(curr->parent == curr->parent->right)
curr = curr->parent;
if(curr != tree->root)
{
curr = curr->parent->right;
while(curr->left != NULL)
curr = curr->left;
}
curr->left = tmp;
}
else
{
while(curr->left != NULL)
curr = curr->left;
curr->left = tmp;
}
}
else
{
fprintf(stderr,"Error\n");
}
tree->last = tmp;
tree->numelm++;
}
{}on a separate line and have pairs align on the same column. I.e. newline before each, indent after a{and outdent before a}. That scheme is widely used on StackOverflow. But it remains an opinion. Using any consistent scheme is fine. - Yunnoschelsein the first column. If you did your indentation consistently that should not be possible. I am currently trying to find the source of this.... It is entirely possible that this inconsistency in indentation indicates an inconsistency in logic or at least syntax. I recommend to join me in trying to find the root of this, because it might lead to solving the actual problem you are asking about.... - Yunnosch{but nine occurrences of}. You need to double check your symmetry. I did not try, but this should mean that the function cannot be compiled as is. Make sure that you provide a minimal reproducible example please. - Yunnosch