vlambda博客
学习文章列表

二叉树的序列化及反序列化

力扣:297题。序列化:将一个数据结构或对象转换为连续的比特位的操作,进而可以将转换后的数据存储在一个文件或内存中,同事也可以通过网络传输到另一个计算环境中,采取相反方式重构得到原数据。

    请设计一个算法来实现二叉树的序列化与反序列化,这里不限定你的序列化与反序列化逻辑,只要保证一个二叉树可以被序列化为一个字符串,并可以将这个字符串反序列化为原始的树即可。

    思路:通过二叉树的前序遍历来实现。误区,没有好好理解题意,不用非要加”[]“,来与案例一样。

public class Codec { //Encodes a tree to a single string    //利用队列的方式实现 public String serialize(TreeNode root){ Queue<TreeNode> queue = new LinkedList<>(); if (root !=null){ queue.add(root); } StringBuffer buffer = new StringBuffer(); buffer.append("["); while (!queue.isEmpty()){ TreeNode poll = queue.poll(); String value =String.valueOf(poll.val); buffer.append(value).append(","); if (poll.left !=null){ queue.add(poll.left); }else { value= "null"; buffer.append(value).append(","); } if (poll.right !=null){ queue.add(poll.right); }else { value= "null"; buffer.append(value).append(","); } } String s = buffer.toString(); buffer.replace(s.length()-1,s.length(),"]"); String result = buffer.toString(); return result; }
public String serialize1(TreeNode root) { return rserialize(root, ""); } public String rserialize(TreeNode root, String str) { if (root == null) { str += "None,"; } else { str += str.valueOf(root.val) + ","; str = rserialize(root.left, str); str = rserialize(root.right, str); } return str; }

//Decodes your encoded data to tree public TreeNode deserialize(String data){ String[] split = data.split(","); ArrayList<String> data_list = new ArrayList<>(Arrays.asList(split)); return reserialize(data_list); } private TreeNode reserialize(ArrayList<String> data_list) { if (data_list.get(0).equals("None")){ data_list.remove(0); return null; } TreeNode node = new TreeNode(Integer.valueOf(data_list.get(0))); data_list.remove(0); node.left = reserialize(data_list); node.right = reserialize(data_list); return node; }}class TreeNode{ int val; TreeNode left; TreeNode right; TreeNode(int x) { val = x; }}