0

Using example from documentation:

from anytree import Node, RenderTree, AsciiStyle

f = Node("f")
b = Node("b", parent=f)
a = Node("a", parent=b)
d = Node("d", parent=b)
c = Node("c", parent=d)
e = Node("e", parent=d)
g = Node("g", parent=f)
i = Node("i", parent=g)
h = Node("h", parent=i)
print(RenderTree(f, style=AsciiStyle()).by_attr())

f 
|-- b
|   |-- a
|   +-- d
|       |-- c
|       +-- e
+-- g
    +-- i
        +-- h

The tree in my case is an internal representation of a file format. At some point I want to write it to a file. The format commands that each node has an opening and a closing tag. (like in html or xml but it's binary format).

If a node is a leaf it's easy to realize it needs a close tag but not for higher level nodes. Using PreOrderIterI would need to output this:

open f -> f -> open b -> b -> open a -> a -> close a -> open d -> d -> open c -> c -> close c-> open e -> e-> close e -> close d -> close b

And so forth. Issue is how I can realize a nodes children have all been traversed and then write close tag?

beginner_
  • 7,230
  • 18
  • 70
  • 127
  • 1
    You would use [post-order traversal](https://en.wikipedia.org/wiki/Tree_traversal#Post-order_(LRN)) for this. In your traversal function, you `print` the current node, call function on all children, and then `print` close + the current node. – Captain Trojan Dec 04 '20 at 11:10
  • My bad. There is also a opening tag. Edited question reflecting that. – beginner_ Dec 04 '20 at 11:17

1 Answers1

2

No worries. You can still do something like

def traverse(node):
    print("open " + node + " -> " + node + " -> ")
    for child in node.children:
         traverse(child)
    print("close " + node + " -> ")
Captain Trojan
  • 2,800
  • 1
  • 11
  • 28