2-3-4树之总结
花了两天的时间终于搞定了这原以为会很容易的一个小程序--实现对一个2-3-4树的插入操作。之所以花这么长时间,主要原因是走了很多弯路,犯了一些常识性的错误,为了防止重犯此类错误,故作此小记,以加深印象。
首先,在开始写程序的时候就没搞清楚2-3-4树的概念,虽然也查了一些资料,但这种很抽象的东西还是有些难以理解,维基百科上实际上已经将2-3-4树的算法步写出来了,但我反复读了二三十遍才看明白。还是直接总结经验吧,条理分明些。
- 在框架还没有搭好之前,不要写细节代码。先用system.out.println()进行测试,测试成功了再开始具体实现。
- 在算法步骤没有彻底想明白之前,不要写任何一行代码。最好先画几张示意图,在图上通过了之后,再开始写。
- 不要改变传入函数的参数,否则就不要传引用进去
- 在写代码之前,先用自然语言将算法步描述出来,这些自然语句可以放入注释中。
- 程序的各个代码段之间的分工要明确。
顺便插入维基百科上对2-3-4树插入算法的描述:
To insert a value, we start at the root of the 2-3-4 tree:
- If the current node is a 4-node:
- Push the middle element of the 4-node up into the parent, leaving a 3-node.
- Split the remaining 3-node up into a pair of 2-nodes.
- If this is the root node (which thus has no parent), the middle value becomes the new root 2-node and the tree height increases by 1. Ascend into the root.
- Otherwise, push the middle value up into the parent node. Ascend into the parent node.
- Find the child whose interval contains the value to be inserted.
- If the child is empty, insert the value into current node and finish.
- Otherwise, descend into the child and repeat from step 1.