BinaryTree* deleteNode1(int val, BinaryTree *tree) { BinaryTree *res=NULL; res = malloc(sizeof(BinaryTree)); if(haveNode(val,tree))//condition : le noeud est présent { if(nodeValue(tree)==val)// si le noeud est trouvée { if(rightChild(tree)==NULL)// sous arbre droit nul on retourne le sous arbre gauche { res=leftChild(tree); } else// sous arbre gauche nul on retourne le sous arbre droit { res=rightChild(tree); } } else// sinon on cherche dans les sous arbres droits et gauches { res=createNodeWithChilds(deleteNode1(val,leftChild(tree)),nodeValue(tree),deleteNode1(val,rightChild(tree))); } } else// si le noeud n'est pas présent, on retourne l'arbre d'entrée { res=tree; } return res; }
BinaryTree* deleteNode(int val, BinaryTree *tree) { if(haveNode(val,tree))//condition : le noeud est présent { switch(numberOfLeaf(tree,val)){//test du nombre de fils et appel de la fonction adequate case 0: return deleteLeaf(val,tree); break; case 1: return deleteNode1(val,tree); break; case 2: return deleteNode2(val,tree); break; default: return tree; break; } } else { return tree; } }
int main(){ struct node *head; /* Create following linked list 12->15->10->11->5->6->2->3 */ push(&head,3); push(&head,10); push(&head,10); push(&head,15); push(&head,12); printf("Given Linked List: "); printList(head); deleteNode1(head, 12); deleteNode1(head, 10); deleteNode1(head, 3); printf("Modified Linked List: "); printList(head); return 0; }
BinaryTree* deleteNode2(int val, BinaryTree *tree) { BinaryTree *res=NULL; res = malloc(sizeof(BinaryTree)); if(haveNode(val,tree))//condition : le noeud est present { if(nodeValue(tree)==val)// on se deplace dans le branches de l'arbre { // on supprime le noeud val dans l'arbre ou a été échangé val et le noeud de valeur maximale dans le sous arbre gauche res=deleteNode1(val,switchNode(val,maxNode(leftChild(tree)),tree)); } else// appel recursif { res=createNodeWithChilds(deleteNode2(val,leftChild(tree)),nodeValue(tree),deleteNode2(val,rightChild(tree))); } } else { res=tree; } return res; }