Serialization is the process of converting a data structure or object into a sequence of bits so that it can be stored in a file or memory buffer, or transmitted across a network connection link to be reconstructed later in the same or another computer environment.
Design an algorithm to serialize and deserialize a binary search tree. There is no restriction on how your serialization/deserialization algorithm should work. You just need to ensure that a binary search tree can be serialized to a string and this string can be deserialized to the original tree structure.
The encoded string should be as compact as possible.
Note: Do not use class member/global/static variables to store states. Your serialize and deserialize algorithms should be stateless.
序列化一颗二叉搜索树,可以和序列化反序列化二叉树用相同的做法,这次就用层次遍历来做。
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class Codec { // Encodes a tree to a single string. public String serialize(TreeNode root) { if(root == null) return ""; StringBuilder str = new StringBuilder(); LinkedList<TreeNode> queue = new LinkedList<>(); queue.offer(root); while(!queue.isEmpty()){ int len = queue.size(); LinkedList<TreeNode> temp = new LinkedList<>(); for(int i = 0; i < len; ++i){ TreeNode node = queue.removeFirst(); if (node != null) { temp.add(node.left); temp.add(node.right); str.append(node.val).append(","); } else { str.append("#,"); } } queue = temp; //System.out.println(queue.toString()); } return str.toString(); } // Decodes your encoded data to tree. public TreeNode deserialize(String data) { if(data == "" || data == null) return null; String[] strs = data.split(","); Queue<String> l = new ArrayDeque<>(Arrays.asList(strs)); Queue<TreeNode> nodes = new ArrayDeque<>(); TreeNode root = new TreeNode(Integer.parseInt(l.poll())); nodes.offer(root); while(!nodes.isEmpty() && !l.isEmpty()){ TreeNode node = nodes.poll(); String strl = l.poll(); if(!strl.equals("#")){ node.left = new TreeNode(Integer.parseInt(strl)); nodes.offer(node.left); } String strr = l.poll(); if(!strr.equals("#")){ node.right = new TreeNode(Integer.parseInt(strr)); nodes.offer(node.right); } } return root; } } // Your Codec object will be instantiated and called as such: // Codec codec = new Codec(); // codec.deserialize(codec.serialize(root));
LeetCode 449. Serialize and Deserialize BST 序列化和反序列化二叉搜索树 (Java)
原文:https://www.cnblogs.com/silentteller/p/12382910.html