The serialization and deserialization of a tree
1) serialization and deserialization of the two-fork tree; the use of a pre-order.
1 PackageCom.tree;2 3 Importjava.util.LinkedList;4 ImportJava.util.Queue;5 6 //serializes a two-pronged tree into a string;7 //and deserializes a string into a tree.8 Public classtreenode_serialization {9 Public Static voidMain (string[] args) {TenTreenode_serialization s =Newtreenode_serialization (); OneString str = "2!3!10!#!#!12!123!#!#!#!18!100!#!#!#!";//Pre-order ATreeNode node =S.pre_deserializationtreenode (str); - s.test (node); - System.out.println (); the System.out.println (S.pre_serializtreenode (node)); - } - //serializes a two-pronged tree into a string - PublicString pre_serializtreenode (TreeNode tree) { + if(Tree = =NULL) { - return"#!"; + } AString str = tree.val + "!"; atstr + =Pre_serializtreenode (tree.left); -str + =Pre_serializtreenode (tree.right); - returnstr; - } - //deserializes a string into a tree;//deserialization of a pre-sequence traversal - PublicTreeNode Pre_deserializationtreenode (String str) { instring[] Arrstr = Str.split ("!"); -Queue<string> qu =NewLinkedlist<string>(); to for(String s:arrstr) { + Qu.add (s); - } the returnPre_deserializationtreenodecore (qu); * } $ //Pre-sequence traversal deserialization. Panax Notoginseng PrivateTreeNode Pre_deserializationtreenodecore (queue<string>qu) { -String str =Qu.poll (); theTreeNode tree =NewTreeNode (); + if("#". Equals (str)) { A return NULL; the } +Tree.left =Pre_deserializationtreenodecore (qu); -Tree.val =integer.valueof (str); $Tree.right =Pre_deserializationtreenodecore (qu); $ returnTree; - } - Public voidTest (TreeNode tree) { the if(Tree! =NULL) { - test (tree.left);WuyiSystem.out.print (Tree.val + ""); the test (tree.right); - } Wu } -}
View Code
2) serialization and deserialization of the two-fork tree; A hierarchical traversal is used.
Second, the traversal of the tree (before and after the "recursive and non-recursive", hierarchical, showing the structure of the hierarchy traversal)
Data structure algorithm (basic algorithm of tree)