Improving scalability of the modified preorder tree traversal algorithm

后端 未结 3 737
星月不相逢
星月不相逢 2021-02-01 10:23

I\'ve been thinking about the modified preorder tree traversal algorithm for storing trees within a flat table (such as SQL).

One property I dislike about the standard a

相关标签:
3条回答
  • 2021-02-01 10:40

    You can split your table into two: the first is (node ID, node value), the second (node ID, child ID), which stores all the edges of the tree. Insertion and deletion then become O(tree depth) (you have to navigate to the element and fix what is below it).

    The solution you propose looks like a B-tree. If you can estimate the total number of nodes in your tree, then you can choose the depth of the tree beforehand.

    0 讨论(0)
  • 2021-02-01 10:47

    I have heard of people doing this before, for the same reasons, yes.

    Note that you do lose at a couple of small advantages of the algorithm by doing this

    • normally, you can tell the number of descendants of a node by ((right - left + 1) div 2). This can occasionally be useful, if e.g. you'd displaying a count in a treeview which should include the number of children to be found further down in the tree
    • Flowing from the above, it's easy to select out all leaf nodes -- WHERE (right = left + 1).

    These are fairly minor advantages and may not be useful to you anyway, though for some usage patterns they're obviously handy.

    That said, it does sound like materialized paths may be more useful to you, as suggested above.

    0 讨论(0)
  • 2021-02-01 10:52

    I think you're better off looking at a different way of storing trees. If your tree is broad but not terribly deep (which seems likely for the case you suggested), you can store the complete list of ancestors up to the root against each node. That way, modifying a node doesn't require touching any nodes other than the node being modified.

    0 讨论(0)
提交回复
热议问题