BACKGROUND
The B+ tree is a kind of Balanced tree which is used to manipulate indexes saving in the relational database system. By using B+ tree, it is faster to retrieve targetted record in the heap file.
In this essay, let me introduce the recent implementation of printing B+ tree in one of my current project.
As usual, B+ has a low level and multiple fanout number, and its non-leaf has a different structure from leaf node. In database lower layer, non-leaf contains multiple keys to search for different leaves. And leaf node contains real key value and RID of record (can be used to get record from heap file).
Analyse
In normal situation, B+ tree has a printing structure as below:
1 | { |
Its tree-formatted structure is like below
We could see from what we mentioned, the non-leaf of B+ tree has “keys” and “children”, but the leaf only has “keys”.
So the printing of leaf and non-leaf is different, we could use different situation in our BFS Algorithm.
Further, The end of each printing component doesn’t have ‘,’. About this problem, we print the first one in the beginning, then print “,” + left one iteratively.
In a corner case, only one leaf node and each entry has same key value, i. e. if leaf entries contain duplicate values, there’s no duplicate key printing anymore, and the RID of it should be in the same quotation marks of former one’s. I designed a way to avoid this problem : remember the former keys when handling leaves, and forget them in the suitable time.
Implementation
The code is below, I use a DFS recursive way to print the entire tree. For the short height of B+ tree, my recursive way cannot lead to the overflow of heap. My code is in the following.
1 |
|
The Thought line of the above code is drew in the following picture:
As for the third situation, it has multiple adjacent leaf node, picture like below :
1 | {"keys":["00000:[(87,0),(84,0),(81,0),(78,0),(75,0),(72,0),(69,0),(66,0),(63,0),(60,0),(57,0),(54,0),(51,0),(48,0),(45,0),(42,0),(39,0),(36,0),(33,0),(30,0),(27,0),(24,0),(21,0),(18,0),(15,0),(12,0),(9,0),(6,0),(3,0),(0,0)]","00001:[(88,1),(85,1),(82,1),(79,1),(76,1),(73,1),(70,1),(67,1),(64,1),(61,1),(58,1),(55,1),(52,1),(49,1),(46,1),(43,1),(40,1),(37,1),(34,1),(31,1),(28,1),(25,1),(22,1),(19,1),(16,1),(13,1),(10,1),(7,1),(4,1),(1,1)]","00002:[(89,2),(86,2),(83,2),(80,2),(77,2),(74,2),(71,2),(68,2),(65,2),(62,2),(59,2),(56,2),(53,2),(50,2),(47,2),(44,2),(41,2),(38,2),(35,2),(32,2),(29,2),(26,2),(23,2),(20,2),(17,2),(14,2),(11,2),(8,2),(5,2),(2,2)]"]} |
Reference :
Database Management System, third edition, Ramakrishnan Gehrke, 2003.