void bitree_remove_right(BiTree *tree, BiTreeNode *node) { BiTreeNode **position; /* do not allow removal from an empty tree */ if (bitree_size(tree) == 0) return; /* determine where to remove nodes */ if (node == NULL) position = &tree->root; else position = &node->right; /* remove the nodes - recursive */ if (*position != NULL) { bitree_remove_left(tree, *position); bitree_remove_right(tree, *position); if (tree->destroy != NULL) { /* call a user defined function to free dynamically allocated data */ tree->destroy((*position)->data); } free(*position); *position = NULL; /* adjust the size of the tree to account for the remoced node */ --tree->size; } }
void bitree_destroy(BiTree *tree) { /* remove all the nodes form the tree */ bitree_remove_left(tree, NULL); /* no operations are allowed now, but clear the structure as a precatuion */ memset(tree, 0, sizeof(BiTree)); }
int main(){ setup(); puts("Add 0-item as BT1's root, BT1: "); bitree_add_left(bt1, NULL, u[0]); bitree_dump(bt1, print); puts(""); puts("Add 1-item as BT2's root, BT2: "); bitree_add_left(bt2, NULL, u[1]); bitree_dump(bt2, print); puts(""); puts("Add 2-item as BT1's root's left child "); bitree_add_left(bt1, bitree_root(bt1), u[2]); puts("Add 3-item as BT1's root's right child "); bitree_add_right(bt1, bitree_root(bt1), u[3]); puts("BT1: "); bitree_dump(bt1, print); puts(""); puts("Add 4-item as BT2's root's left child "); bitree_add_left(bt2, bitree_root(bt2), u[4]); puts("Add 5-item as BT2's root's right child "); bitree_add_right(bt2, bitree_root(bt2), u[5]); puts("BT2: "); bitree_dump(bt2, print); puts(""); printf("BT1 len: %d\n", bitree_size(bt1)); printf("BT2 len: %d\n", bitree_size(bt2)); printf("BT len: %d\n", bitree_size(bt)); puts("Merge BT1 and BT2 to BT: "); bitree_merge(bt, bt1, bt2, u[6]); bitree_dump(bt, print); puts(""); printf("BT len: %d\n", bitree_size(bt)); puts("BT remove left child, BT: "); bitree_remove_left(bt, bitree_root(bt)); bitree_dump(bt, print); puts(""); enddown(); return 0; }
void bitree_remove_right(Bitree *tree, BiTreeNode *node) { BiTreeNode **position; if (bitree_size(tree) == 0) return; if (node == NULL) position = &tree->root; else position = &node->right; if (*position != NULL) { bitree_remove_right(tree, *position); bitree_remove_left(tree, *position); if (tree->destory != NULL) tree->destory((*position)->data); free(*position); *position = NULL; tree->size--; } return; }