简体   繁体   中英

Generic traversal of tree structure

I'm trying to write my tree (well, it's binary trie) traversal more generic, because the way it is now I have very similar code repeated.

I'm walking the tree in lexicographical inorder. The example of functions I think can be abstracted by universal tree traversal are (in pseudocode):

items(node*, key, list&) {
    if(node->value)
        list.push({node->value, key})
    if(node->left)
        items(node->value, key + "0")
    if(node->right)
        items(node->value, key + "1")
}

draw(node*, id, ostream&) {
    drawNode(node, id)
    if (node->left)
        drawLine(node, node->left, "0", ostream&)
        draw(node->left, ++id, ostream&)
    if (node->right)
        drawLine(node, node->right, "1", ostream&)
        draw(node->right, ++id, ostream&)

I'm not asking for functioning code, just a push in the right direction. Should it be done with templates taking functions as arguments? What about more complicated cases, where the traversal is not simply conditioned by existence of single left/right node (the merging of two trie seems too like a candidate for this abstraction).

The generic abstraction of traversal is a suitable form of iterator. Once the traversal has become a linear sequence of positions you'd formulate it using one of the conventional iterators, most likely modeling BidirectionalIterator. When generalizing traversal of trees (or more general, graphs) you may have iteration operations moving in different directions.

Necroposting, but still probably worth it if anyone lands on this question.

Generic tree traversal was studies by theorists of the functional programming and they eventually produced several usable libraries for haskell. I will point at recursion-schemes and syb (scrap your borderplate) libraries. Both come with a paper describing the approach taken.

Syb relies on a form of runtime reflection and uses quite a bit of type casts/coercion, but recursion-schemes were ported to several languages including kotling and scala, so they are compatible with imperative languages.

By no means those works represent pinnacle of what can be done with recursive traversal of tree-like datastructures, but they see some use and the ideas are well-tested.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM