MTree.h
#pragma once
#include <vector>
using namespace std;
//节点的关键字和子节点的指针对是
//p0 p1 p2 ... p(n-1) pn
//k0 k1 k2 ... k(n-1)
//而不是象教材里的
//p0 p1 p2 ... p(n-1) pn
// k1 k2 ... k(n-1) kn
template <typename T>
class MTreeNode
{
public:
MTreeNode(int _m_routeCount) : m_routeCount(_m_routeCount) {
m_keyNumber = 0;
pChildsArray = new MTreeNode<T>*[m_routeCount];
keys = new T[m_routeCount - 1];
for (int i = 0; i < m_routeCount; ++i) {
pChildsArray[i] = NULL;
if (i != m_routeCount - 2)
keys[i] = 0;
}
}
virtual ~MTreeNode() {
delete[] pChildsArray;
delete[] keys;
}
MTreeNode<T>** pChildsArray;
T* keys;
int m_keyNumber;
int m_routeCount;
};
//多路搜索树
template <typename T>
class MTree {
public:
int RouteCount;
MTreeNode<T>* Root;
void AddValue(MTreeNode<T>* &tmpNode, T t) {
if (tmpNode == NULL) {
tmpNode = new MTreeNode<T>(RouteCount);
}
int pindex = 0;
//默认插入到当前节点的某个关键字里
bool bInsertIntoChildNode = false;
for (int i = 0; i < tmpNode->m_keyNumber; ++i) {
if (t < tmpNode->keys[i]) {
pindex = i;
//如果要插入的值小于当前节点的某个关键字,则插入到子节点里
bInsertIntoChildNode = true;
break;
} else {
pindex = i + 1;
}
}
//tmpNode的关键码未存完,存在tmpNode的索引为tmpNode->m_keyNumber的关键字里
if (!bInsertIntoChildNode && tmpNode->m_keyNumber < tmpNode->m_routeCount - 1) {
tmpNode->keys[tmpNode->m_keyNumber++] = t;
} else {
//存在tmpNode->pChildsArray[pindex]所指的节点里
if (tmpNode->pChildsArray[pindex] == NULL)
tmpNode->pChildsArray[pindex] = new MTreeNode<T>(RouteCount);
AddValue(tmpNode->pChildsArray[pindex], t);
}
}
/*void AddValue(MTreeNode<T>* &tmpNode, T t) {
if (tmpNode == NULL) {
tmpNode = new MTreeNode<T>(RouteCount);
}
//根节点关键字未满
if (tmpNode->m_keyNumber < RouteCount - 1) {
//while (tmpNode->m_keyNumber < RouteCount - 1) {
tmpNode->keys[tmpNode->m_keyNumber++] = t;
//}
} else {
int pindex = 0;
for (int i = 0; i < tmpNode->m_keyNumber; ++i) {
if (t < tmpNode->keys[i]) {
pindex = i;
break;
} else{
pindex = tmpNode->m_routeCount - 1;
}
}
if (tmpNode->pChildsArray[pindex] == NULL)
tmpNode->pChildsArray[pindex] = new MTreeNode<T>(RouteCount);
AddValue(tmpNode->pChildsArray[pindex], t);
}
}*/
};
MTreeDemo.cpp
#include "stdafx.h"
#include "MTree.h"
int _tmain(int argc, _TCHAR* argv[])
{
MTree<int> *root = new MTree<int>();
root->RouteCount = 3;
root->AddValue(root->Root, 18);
root->AddValue(root->Root, 42);
root->AddValue(root->Root, 8);
root->AddValue(root->Root, 14);
root->AddValue(root->Root, 22);
root->AddValue(root->Root, 29);
root->AddValue(root->Root, 44);
root->AddValue(root->Root, 52);
root->AddValue(root->Root, 20);
root->AddValue(root->Root, 33);
return 0;
}