二叉树的序列化和反序列化
前序遍历的序列化与反序列化
/** * Created by Skye on 2018/4/25. * 二叉树的序列化和反序列化 * 0 * 1 2 * 3 4 5 6 * 7 / 8 / 9 / */ public class SerializeAndReconstructTree { //前序遍历的序列化 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){ //以分隔符_为标志,将字符串分割为一个一个的结点,组成一个数组 String []values = str.split("_"); //队列:用来盛放数组中的字符,这样可以在后面每次出队列一个字符,就省去了使用数组的话,还要有一个额外的指针来指向当前结点 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 ); //前序遍历 0 1 3 7 4 8 2 5 9 6 //中序遍历 7 3 1 4 8 0 5 9 2 6 //后序遍历 7 3 8 4 1 9 5 6 2 0 //层序遍历 0 1 2 3 4 5 6 7 8 9 String serialize = serialBinaryTree( tree ); System.out.println(serialize); Tree root = reconstructTree( serialize ); inOrder( root ); } }