static TNode *removeRecursive(TNode *pRoot, const void *pKey, CompareFunc compare) { int result; TNode *pNodeSuccessor, *pNodeDelete; if (pRoot != NULL) { if ((result = compare(pRoot->pData, pKey)) > 0) { pRoot->pLeft = removeRecursive(pRoot->pLeft, pKey, compare); } else if (result < 0) { pRoot->pRight = removeRecursive(pRoot->pRight, pKey, compare); } else { if (pRoot->pLeft == NULL) { pNodeDelete = pRoot; pRoot = pRoot->pRight; delete pNodeDelete; } else if (pRoot->pRight == NULL) { pNodeDelete = pRoot; pRoot = pRoot->pLeft; delete pNodeDelete; } else { pNodeSuccessor = getInorderSuccessor(pRoot->pRight); pRoot->pData = pNodeSuccessor->pData; pRoot->pRight = removeRecursive(pRoot->pRight, pNodeSuccessor->pData, compare); } } return pRoot; } else { return NULL; } }
struct AVLnode* remove_node(struct AVLnode* root, int data) { if (!root) return root; // search for element if (data < root->data) root->left = remove_node(root->left, data); else if (data > root->data) root->right = remove_node(root->right, data); else { // data is found // node to be deleted is leaf if (!root->left && !root->right) { free(root); root = NULL; } // node to be deleted has one child else if (!root->right)// has left child { struct AVLnode* temp = root; root = root->left; free(temp); } else if (!root->left)// has right child { struct AVLnode* temp = root; root = root->right; free(temp); } else { // node has two children struct AVLnode* inorderSuccessor = getInorderSuccessor(root->right); root->data = inorderSuccessor->data; root->right = remove_node(root->right, inorderSuccessor->data); } } return root; }