How do you sort a tree stored using the nested set model?

前端 未结 8 758
不思量自难忘°
不思量自难忘° 2021-01-31 20:32

When I refer to nested set model I mean what is described here.

I need to build a new system for storing \"categories\" (I can\'t think of better word for it) in a user

8条回答
  •  自闭症患者
    2021-01-31 20:51

    I believe that, in your case, where the nodes you want to swap don't have any descendants, you can simply swap the lft and rgt values around. Consider this tree:

       A
     /   \
    B     C
         / \
        D   E
    

    This could turn into this group of nested sets:

    1 A 10 
    2 B 3  
    4 C 9
    5 D 6
    7 E 8
    

    Now consider you want to swap D and E. The following nested sets are valid and D and E are swapped:

    1 A 10
    2 B 3 
    4 C 9 
    7 D 8
    5 E 6 
    

    Swapping nodes that have subtrees cannot be done this way, of course, because you would need to update the childrens' lft and rgt values as well.

提交回复
热议问题