Académique Documents
Professionnel Documents
Culture Documents
5 2 7 9 12
15 20 17
5 2 7 9 12
15 20 17
5 2 7 9 12
15 20 17
5 2 7 9 12
15
13
How to delete a node from binary search tree? An pointer which can revise C Program codes:
the link from parent node The node you want to delete
void deleteNode(TreeNodePtr * treePtr, int value){ TreeNodePtr current = * treePtr, parentPtr, tmpPtr; if(!current){ Get the information of current node fprintf(stderr, "The tree is empty or has not this node.\n"); return; Return a error messenge for empty tree } or the tree without this node if(current->data == value){ If find the node, following the four cases /*it's a leaf node*/ if(!current->rightPtr && !current->leftPtr){ * treePtr = NULL; Case (a), let the parent node link to NULL, free(current); and free(delete) the node }
left child, and free the current node /*the right child is NULL, and left child isn't*/ else if(!current->rightPtr){ * treePtr = current->leftPtr; free(current); Case (b) and (d), find the smallest node } of the right subtree /*the node has both children*/ else{ Get the right children to decide (b) or (d) tmpPtr = current->rightPtr; /*the rightPtr without left child*/ Case(b), let the left child node link to the if(!tmpPtr->leftPtr) right child, and let the parent node tmpPtr->leftPtr = current->leftPtr; link to the left child.
How to delete a node from binary search tree? C Program codes: Case(c), let the parent node link to the
Case(d), find the smallest node of right subtree /*the rightPtr have left child*/ else{ /*find the smallest node in right subtree*/ while(tmpPtr->leftPtr){ Find the smallest node, and record /*record the parent node of tmpPtr*/ its parent node parentPtr = tmpPtr; tmpPtr = tmpPtr->leftPtr; Let the parent node of smallest node } link to the right child of smallest node parentPtr->leftPtr = tmpPtr->rightPtr; tmpPtr->leftPtr = current->leftPtr; Let right child of the smallest node tmpPtr->rightPtr = current->rightPtr; link to the left child of current node, } so as the right one
Let the parent node of current node link to * treePtr = tmpPtr; The smallest node, and free the current node free(current); If the node you want to delete is big than } current node, find the right child }else if(value > current->data){/*search the node*/ deleteNode(&(current->rightPtr), value); }else if(value < current->data){ deleteNode(&(current->leftPtr), value); If the node is small than current node, } find the left child