![]() When an entry with children is encountered, a new node is pushed on top of the stack. It uses a stack of 'parents' to collect the nodes into a tree hierarchy.Īt each step in the loop the invariant is that the node at the top of the stack is the parent node to which nodes have to be added. Finally add a null entry to signal that the children # of this node have ended lst.append((node.data, True)) for child in node.children: serialize_aux(child) lst.append( None) else: # The node is child-less, so simply add it to # the list & mark that it has no chilren lst.append((node.data, False)) serialize_aux(root_node) return lst And now deserialization. ![]() 按照tree mining的方法encode,稍加改变可作为N-ary tree encoding.Īdd it to the list & mark that it has children # 2. Design an algorithm to serialize and deserialize a binary tree. Serialize and Deserialize an N-ary Tree Print nodes between two given level. '' lst = def serialize_aux(node): # Recursive visitor function if len(node.children) >0: # The node has children, so: # 1. Def serialize_tree(root_node): '' Given a tree root node (some object with a 'data' attribute and a 'children' attribute which is a list of child nodes), serialize it to a list, each element of which is either a pair (data, has_children_flag), or None (which signals an end of a sibling chain). The main idea is to walk the tree recursively in pre-order (first visiting a node, then its children in order), while populating the serialized list which exists outside the recursive visitor. Here they are, with Python (as usual) serving as pseudo-code as well as the implementation.įirst, serialization. A,True B,True E,False F,True G,False None None C,False D,True X,False Y,False None None The algorithms for serializing a tree into this representation and deserializing it back are charmingly simple. ![]() #Serialize And Deserialize A Given N Ary Tree code#I will use Python code to demonstrate the algorithm, so a simplistic tree node would be. First, let's define the data structures involved. It allows serializing generic N-ary trees (where each node can have any number of children) into a linear data structure suitable for storage or tramsmission. In this post I want to present one interesting technique I recently ran into, in the context of the debugging information format. Septemat 06:41 Tags, There are several techniques available for serializing trees. ![]()
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |