/ Published in: C++
Implementacija općenitog stabla
Expand |
Embed | Plain Text
Copy this code and paste it in your HTML
#include <iostream> #define max 1000 using namespace std; struct elem { int label, First_Child, Next_Sibling; }; struct stablo { elem polje[max]; int korijen; }; stablo T; int FirstChildT (int n, stablo T) { return T.polje[n].First_Child; }; int NextSiblingT (int n, stablo T) { return T.polje[n].Next_Sibling; }; int ParentT (int n, stablo T) { for (int I = 0; I < max; I++) if (FirstChildT (I, T) == n) return I; else if (NextSiblingT (I, T) == n) return ParentT (I, T); return -1; }; int LabelT (int n, stablo T) { return T.polje[n].label; }; int RootT (stablo T) { return T.korijen; }; int CreateT (int x, int n, stablo &T) { int temp = 1; while (LabelT (temp, T) != -1) temp++; T.polje[temp].label = x; T.polje[temp].First_Child = -1; T.polje[temp].Next_Sibling = -1; if (T.polje[n].First_Child != -1) { n = FirstChildT (n, T); while (NextSiblingT (n, T) != -1) n = NextSiblingT (n, T); T.polje[n].Next_Sibling = temp; } else T.polje[n].First_Child = temp; return temp; }; void ChangeLabelT (int x, int n, stablo &T) { T.polje[n].label = x; }; void DeleteT (int n, stablo &T) { int temp; if (FirstChildT (n, T) != -1) { temp = FirstChildT (n, T); DeleteT (temp, T); while (NextSiblingT (temp, T) != -1) { temp = NextSiblingT (temp, T); DeleteT (temp, T); } } T.polje[n].label = -1; if (n != RootT (T) && FirstChildT (ParentT (n, T), T) == n) T.polje[ParentT (n, T)].First_Child = NextSiblingT (n, T); else if (n != RootT (T)) { temp = FirstChildT (ParentT (n, T), T); while (NextSiblingT (temp, T) != n) temp = NextSiblingT (temp, T); T.polje[temp].Next_Sibling = NextSiblingT (n, T); } }; void InitT (int x, stablo &T) { T.korijen = 1; T.polje[1].label = x; T.polje[1].First_Child = -1; T.polje[1].Next_Sibling = -1; T.polje[0].label = -1; T.polje[0].First_Child = -1; T.polje[0].Next_Sibling = -1; for (int I = 2; I < max; I++) { T.polje[I].label = -1; T.polje[I].First_Child = -1; T.polje[I].Next_Sibling = -1; } } void PreOrderT (int temp) { cout << LabelT (temp, T) << ", "; if (FirstChildT (temp, T) != -1) PreOrderT (FirstChildT (temp, T)); if (NextSiblingT (temp, T) != -1) PreOrderT (NextSiblingT (temp, T)); } void InOrderT (int temp) { if (FirstChildT (temp, T) != -1) InOrderT (FirstChildT (temp, T)); cout << LabelT (temp, T) << ", "; if (FirstChildT (temp, T) != -1) { temp = FirstChildT (temp, T); while (NextSiblingT (temp, T) != -1) temp = NextSiblingT (temp, T), InOrderT (temp); } } void PostOrderT (int temp) { if (FirstChildT (temp, T) != -1) PostOrderT (FirstChildT (temp, T)); int pom = temp; if (FirstChildT (pom, T) != -1) { pom = FirstChildT (pom, T); while (NextSiblingT (pom, T) != -1) pom = NextSiblingT (pom, T), PostOrderT (pom); } cout << LabelT (temp, T) << ", "; }