您的位置:首页 > 编程语言 > Java开发

2-3-4树的分裂核心代码【JAVA实现】

2009-12-06 15:59 309 查看
2-3-4树节点分裂分两种情况。
1:节点分裂;2:根的分裂。

先要分裂的数据项设为A,B,C

节点分裂

1.创建一个新的空节点。它是要分裂节点的兄弟,在要分裂节点的右边。
2.数据项C转移到新节点上。
3.数据项B转移到要分裂节点的父节点上。
4.数据项A保留在原来的节点上。
5.最右边的两个子节点从要分裂节点处断开,连接到新节点上。

根的分裂

1.创建新的节点,作为根。它是要分裂节点的父节点。
2创建第二个新的空节点。它是要分裂节点的兄弟,在要分裂节点的右边。
3数据项C转移到新节点上。
4数据项B转移到要分裂节点的父节点上。
5数据项A保留在原来的节点上。
6.最右边的两个子节点从要分裂节点处断开,连接到新节点上。

代码

public void split(Node thisNode)     // split the node
{
// assumes node is full
DataItem itemB, itemC; //数据项B,C
Node parent, child2, child3;//thisNode节点父节点,第3、4个子节点
int itemIndex;

itemC = thisNode.removeItem();    // 数据项C从thisNode节点移除
itemB = thisNode.removeItem();    // 数据项B从thisNode节点移除

child2 = thisNode.disconnectChild(2); // 节点的第3个子节点从节点中断开
child3 = thisNode.disconnectChild(3); //节点的第4个子节点从节点中断开

Node newRight = new Node();       // make new node

if(thisNode==root)                // 如果是根节点,创建新的节点,作为根。它是要分裂节点的父节点。
{
root = new Node();                // make new root
parent = root;                    // root is our parent
root.connectChild(0, thisNode);   // connect to parent
}
else                              // this node not the root
parent = thisNode.getParent();    // 得到节点的父节点

// deal with parent
itemIndex = parent.insertItem(itemB); // 将数据项B插入父节点,并返回插入的位置
int n = parent.getNumItems();         // 父节点的数据项总数

/*
*将父节点中子节点移动到合适的位置
*/
for(int j=n-1; j>itemIndex; j--)          // move parent's
{                                      // connections
Node temp = parent.disconnectChild(j); // one child
parent.connectChild(j+1, temp);        // to the right
}
// connect newRight to parent
parent.connectChild(itemIndex+1, newRight);//新节点与父节点相连

// deal with newRight
newRight.insertItem(itemC);       // item C to newRight
newRight.connectChild(0, child2); // connect to 0 and 1
newRight.connectChild(1, child3); // on newRight
}  // end split()

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: