Serialization and deserialization of binary trees Serialization and deserialization
of preorder traversal
/** * Created by Skye on 2018/4/25. * Serialization and deserialization of binary trees * 0 * 1 2 * 3 4 5 6 * 7 \ / 8 / 9 / \ */ public class SerializeAndReconstructTree { // Serialization of preorder traversal public static String serialBinaryTree(Tree tree){ if(tree == null) return "#_"; String res = tree.val + "_"; res += serialBinaryTree( tree.left ); res += serialBinaryTree( tree.right ); return res; } public static Tree reconstructTree(String str){ //With the delimiter _ as the mark, the string is divided into nodes one by one to form an array String []values = str.split("_"); //Queue: used to hold the characters in the array, so that one character can be dequeued at a time later, eliminating the need to use the array and having an extra pointer to point to the current node Queue<String> queue = new LinkedList<>(); for(int i = 0; i < values.length; i++){ queue.offer(values[i]); } return reconstruct(queue); } public static Tree reconstruct(Queue<String> queue){ String value = queue.poll(); if("#".equals(value)){ return null; } Tree node = new Tree(Integer.valueOf(value)); node.left = reconstruct( queue ); node.right = reconstruct(queue); return node; } public static void inOrder(Tree tree){ if(tree == null) return; Stack<Tree> stack = new Stack<>(); stack.push(tree); while(!stack.empty()){ tree = stack.pop(); System.out.print(tree.val + " "); if(tree.right != null){ stack.push(tree.right); } if(tree.left != null){ stack.push(tree.left); } } } public static void main(String[] args){ Tree tree = new Tree( 0 ); tree.left = new Tree(1); tree.right = new Tree(2); tree.left.left = new Tree( 3 ); tree.left.right = new Tree( 4 ); tree.left.left.left = new Tree( 7 ); tree.left.right.right = new Tree(8); tree.right.left = new Tree( 5 ); tree.right.right = new Tree( 6 ); tree.right.left.right = new Tree( 9 ); //Preorder traversal 0 1 3 7 4 8 2 5 9 6 //Inorder traversal 7 3 1 4 8 0 5 9 2 6 //Postorder traversal 7 3 8 4 1 9 5 6 2 0 //Level order traversal 0 1 2 3 4 5 6 7 8 9 String serialize = serialBinaryTree( tree ); System.out.println(serialize); Tree root = reconstructTree( serialize ); inOrder( root ); } }