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){ //degenarate
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++;
}
Aucun commentaire:
Enregistrer un commentaire