/ Published in: C++
Implementacija općenitog stabla „prvo dijete - sljedeći brat“ pomoću polja za kolegij Strukture podataka.
Expand |
Embed | Plain Text
Copy this code and paste it in your HTML
struct elem{ char label; int firstchild, nextsibling; }; struct tree{ elem array[10000]; int root; }; tree* InitT(int x, tree* T){ T = new tree; for(int i=0; i<1000; i++){ T->array[i].label = '0'; T->array[i].firstchild = -1; T->array[i].nextsibling = -1; } T->array[x].label = 'A'; T->root = x; return T; } int RootT(tree* T){ return T->root; } char LabelT(int n, tree* T){ return T->array[n].label; } char ChangeLabelT(char x, int n, tree* T){ T->array[n].label = x; } int FirstChildT(int n, tree* T){ return T->array[n].firstchild; } int NextSiblingT(int n, tree* T){ return T->array[n].nextsibling; } int ParentT(int n, tree* T){ for(int i=0; i<10000; i++){ if(T->array[i].firstchild == n) return i; if(T->array[i].nextsibling == n) return ParentT(i, T); } } void CreateT(int x, int n, tree* T){ if(T->array[n].label == '0') cout << "Cvor " << n << " ne postoji unutar stabla." << endl; else{ if(T->array[n].firstchild == -1) T->array[n].firstchild = x; else if(T->array[T->array[n].firstchild].nextsibling == -1) T->array[T->array[n].firstchild].nextsibling = x; else{ n = T->array[n].firstchild; while(T->array[n].nextsibling != -1) n = T->array[n].nextsibling; T->array[n].nextsibling = x; } T->array[x].firstchild = -1; T->array[x].nextsibling = -1; T->array[x].label = T->array[n].label+1; } } bool DeleteT(int n,tree *T){ if(T->array[n].firstchild != -1) DeleteT(T->array[n].firstchild,T); if(T->array[n].nextsibling != -1) DeleteT(T->array[n].nextsibling,T); T->array[n].label = '0'; T->array[n].firstchild = -1; T->array[n].nextsibling = -1; if(T->array[ParentT(n,T)].nextsibling != -1) T->array[ParentT(n,T)].firstchild = T->array[ParentT(n,T)].nextsibling; else T->array[ParentT(n,T)].firstchild = -1; return true; }