题目:
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.
分析:利用层次遍历进行序列化,在反序列化时,TreeNode数组中每个节点的left节点下标为2*(i-nullNum)+1,right节点下标为2*(i-nullNum)+2,其中nullNum为TreeNode数组中元素null的个数。
Java代码及注释如下:
// Encodes a tree to a single string. public String serialize(TreeNode root) { // 1,2,3,null,null,4,5,null,null,null,null if (root == null) { return ""; } StringBuilder sb = new StringBuilder(); Queue<TreeNode> queue = new LinkedList<TreeNode>(); queue.offer(root); while (! queue.isEmpty()) { //利用队列进行层次遍历(广搜) TreeNode tmp = queue.poll(); if (tmp != null) { sb.append(tmp.val); queue.offer(tmp.left); queue.offer(tmp.right); } else { sb.append("null"); } sb.append(","); } sb.deleteCharAt(sb.length()-1); return sb.toString(); } // Decodes your encoded data to tree. public TreeNode deserialize(String data) { if ("".equals(data)) { return null; } String[] tmp = data.split(","); TreeNode[] node = new TreeNode[tmp.length]; // 根据序列化数组元素构造TreeNode数组. for (int i = 0; i < node.length; i++) { if ("null".equals(tmp[i])) { node[i] = null; } else { node[i] = new TreeNode(Integer.parseInt(tmp[i])); } } int nullNum = 0; for (int i = 0; i < tmp.length; i++) { //找到TreeNode数组中每个node所指向的left和right节点。 if (node[i] != null) { node[i].left = node[2*(i-nullNum)+1]; node[i].right = node[2*(i-nullNum)+2]; } else { nullNum++; } } return node[0]; //返回root }
时间: 2024-10-17 07:24:14