There are several data structures for this algorithm
1 LfT stands for left
2 RGT represents right
3 the level at which LVL is represented
The following figure is a typical structure
Let's look at some of the ways to use
1 Viewing the entire tree (a) How many nodes (including themselves)
just look at the root node. (right-left+1)/2 = (20-1+1)/2 = ten
This number has 10 nodes .
2 Viewing paths from nodes A through e
SELECT * from tree where lft between 1 and 6 and RGT between 7 and the ORDER by LFT
The result is a,b,d,e the data of these 4 nodes, and according to the Order of access paths
if the relationship between 2 nodes is not hierarchical, the query has no results
the reverse is the same, you can get the bottom of a node, to the path of the ancestor node
SELECT * from tree where lft between 1 and 6 and RGT between 7 and the order by lft Desc
The only difference is that the sort is reversed on the line.
3 gets all the nodes below a node, and returns as a tree structure
we use B as an example.
SELECT * from the tree where lft>2 and right<11 order by LfT
The result is c,d,e,f, and the order is correct.
4 Get all sub-nodes under Level 2
We do an example, this time with the LVL parameter, because the level of a is 1, so we query level is not greater than 3.
SELECT * from tree where lft>2 and right<11 and lvl<=3 order by LfT
let's look at our new method for adding a node.
below the root node, we add an X node to the right of the G node
the job we're going to do is
the right parameter of the 1 G node is
2 Change all affected nodes to make free slots for new nodes
all of the left nodes are larger than the G-node, increasing by 2.
Update tree set lft=lft+2 where lft>12
all of the right nodes are larger than the G-node, increasing by 2.
Update tree set rgt=rgt+2 where rgt>13
3 new nodes placed on empty seats, lft=14,rgt=15
This completes the incremental operation of a new node.
Graphic interpretation of pre-sorted traversal tree algorithm