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 tree. There is no restriction on how your serialization/deserialization algorithm should work. You just need to ensure that a binary tree can be serialized to a string and this string can be deserialized to the original tree structure. For example, you may serialize the following tree 1 / \ 2 3 / \ 4 5 as "[1,2,3,null,null,4,5]", just the same as how LeetCode OJ serializes a binary tree. You do not necessarily need to follow this format, so please be creative and come up with different approaches yourself. Note: Do not use class member/global/static variables to store states. Your serialize and deserialize algorithms should be stateless.
设计一个方法将一个二叉树序列化并反序列化。序列化是指将对象转化成一个字符串,该字符串能够在网络上传输,而且到达目的地后能够经过反序列化恢复成原来的对象。node
在Leetcode中,树的序列化是经过广度优先遍历实现的,就如题目中所介绍的那样。面试
这里咱们使用中序遍从来解决这个问题。微信
中序遍历是指递归的先遍历当前节点,而后按一样的方式递归的遍历左子树,再递归的遍历右子树。所以题目中的例子的中序遍历结果为[1,2,3,4,5]
。可是,标准的中序遍历并不能使咱们将该结果反构形成一棵树,咱们丢失了父节点和子节点之间的关系。所以咱们须要适当的插入空值来保存父节点和子节点的关系。网络
所以,咱们将访问到空值也记录下来,结果以下[1,2, , ,3,4, , ,5, , ]
。app
这里咱们也能够明显的看出来,中序遍历须要保存的空值远远多于广度优先遍历。less
那么咱们如何将这个字符串反序列化呢?
其实思路仍是同样的,将其根据分隔符分割后传入队列,不断从队列头读取数据,先构建当前节点,而后依次构建左子树和右子树,若是遇到空值,则返回递归。ui
代码以下:this
private static final String NULL = "N"; private static final String SPLITOR = ","; // Encodes a tree to a single string. public String serialize(TreeNode root) { StringBuilder result = new StringBuilder(); inOrder(root, result); return result.toString(); } private void inOrder(TreeNode root, StringBuilder result){ if(root==null){ result.append(NULL).append(SPLITOR); }else{ result.append(root.val).append(SPLITOR); inOrder(root.left, result); inOrder(root.right, result); } } // Decodes your encoded data to tree. public TreeNode deserialize(String data) { Deque<String> nodes = new LinkedList<String>(Arrays.asList(data.split(SPLITOR))); return buildTree(nodes); } private TreeNode buildTree(Deque<String> nodes) { String val = nodes.remove(); if (val.equals(NULL)) return null; else { TreeNode node = new TreeNode(Integer.valueOf(val)); node.left = buildTree(nodes); node.right = buildTree(nodes); return node; } }
想要了解更多开发技术,面试教程以及互联网公司内推,欢迎关注个人微信公众号!将会不按期的发放福利哦~spa