Skip to content
Snippets Groups Projects
Commit ae0a6bf8 authored by Peter Gerwinski's avatar Peter Gerwinski
Browse files

weitere Beispielprogramme 3.5.2018

parent 91656146
Branches
No related tags found
No related merge requests found
#include <iostream>
using namespace std;
const int MaxLeaves = 4;
const int MaxEntries = MaxLeaves - 1;
template <typename TElement>
class TTree
{
struct TEntry
{
TElement Content;
bool empty;
TEntry ()
{
empty = true;
}
};
struct TLeaf
{
TEntry Entry[MaxEntries];
TLeaf *Child[MaxLeaves];
TLeaf ()
{
for (int i = 0; i < MaxLeaves; i++)
Child[i] = NULL;
}
void SetEntry (int i, TElement e)
{
Entry[i].Content = e;
Entry[i].empty = false;
}
};
TLeaf *Root;
private:
void SplitLeaf (TLeaf *FullLeaf, TElement NewElement, TLeaf *&Left, TLeaf *&Right, TElement &Middle)
{
int i = 0;
while (i < MaxEntries && NewElement > FullLeaf->Entry[i].Content)
i++;
TElement Top;
if (i < MaxEntries)
{
Top = FullLeaf->Entry[MaxEntries - 1].Content;
for (int j = MaxEntries - 1; j > i; j--)
FullLeaf->Entry[j] = FullLeaf->Entry[j - 1];
FullLeaf->SetEntry (i, NewElement);
}
else
Top = NewElement;
// Achtung: Hier benutzen wir, daß MaxEntries = 3 ist!
Middle = FullLeaf->Entry[2].Content;
FullLeaf->Entry[2].empty = true;
Left = FullLeaf;
Right = new TLeaf ();
Right->SetEntry (0, Top);
}
void PrintLeaf (TLeaf *Leaf)
{
if (Leaf)
{
for (int i = 0; i < MaxEntries; i++)
{
PrintLeaf (Leaf->Child[i]);
if (!Leaf->Entry[i].empty)
cout << Leaf->Entry[i].Content << " ";
}
PrintLeaf (Leaf->Child[MaxLeaves - 1]);
}
}
public:
TTree ()
{
Root = NULL;
}
void Insert (TElement e)
{
if (!Root)
Root = new TLeaf ();
if (Root->Entry[MaxEntries - 1].empty)
{
int i = 0;
while (i < MaxEntries && !Root->Entry[i].empty && e > Root->Entry[i].Content)
i++;
if (i < MaxEntries)
{
if (!Root->Entry[i].empty)
for (int j = MaxEntries - 1; j > i; j--)
Root->Entry[j] = Root->Entry[j - 1];
Root->SetEntry (i, e);
}
}
else
{
TLeaf *Left, *Right;
TElement Middle;
SplitLeaf (Root, e, Left, Right, Middle); // "zerstört" Root
Root = new TLeaf ();
Root->SetEntry (0, Middle);
Root->Child[0] = Left;
Root->Child[1] = Right;
}
}
void Print ()
{
PrintLeaf (Root);
cout << endl;
}
};
int main ()
{
TTree <int> t;
t.Insert (42);
t.Insert (13);
t.Insert (137);
t.Insert (7);
t.Print ();
return 0;
}
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment