LeetCode——Serialize and Deserialize Binary Tree

时间:2023-03-09 07:09:08
LeetCode——Serialize and Deserialize Binary Tree

Description:

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.

本以为二叉树已经刷的比较溜了,但是还是踩了各种坑。。。

题目大意是按照对应的规则序列化和反序列化二叉树。其实就是求二叉树"按层"遍历序列和根据按层遍历序列求二叉树。但是这里的按层遍历是局部对称的,如果一个节点不为null,则就必须存储它的左右子节点,如果子节点为null就存成"null"。注意他的调用方式是先序列化再反序列化如果和原来的树相同的话就是正确的,所以中间返回的序列只要在反序列化时能解析就行,没有固定格式。

思路:序列化时按层遍历,用一个队列来保存当前节点。注意相对于普通的按层遍历,有一个条件不能少,就是在不能使用队列为null作为循环终止条件,因为最后一个叶子节点的左右子节点一定是null的,这样的话序列化的字符串就会多出来“null”,需要加一个判定有效节点个数的条件。如果非要使用队列为null作为唯一循环终止的条件的话就需要在反序列化时去掉序列最后所有的"null"。

AC代码:

 /**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Codec { private int cnt;
// Encodes a tree to a single string.
public String serialize(TreeNode root) {
nodeCount(root);
StringBuilder res = new StringBuilder();
Deque<TreeNode> queue = new LinkedList<TreeNode>();
if(root == null) {
return null;
} queue.offer(root);
int count = 0;
while(count < cnt && !queue.isEmpty()) { TreeNode node = queue.peek();
if(node == null) {
res.append("null ");
queue.poll();
}
else {
res.append(node.val + " ");
count ++;
queue.poll();
if(node.left != null) {
queue.offer(node.left);
}
else {
queue.offer(null);
}
if(node.right != null) {
queue.offer(node.right);
}
else {
queue.offer(null);
}
} }
return res.toString();
} public int treeDepth(TreeNode root) {
int dep = 0;
if(root != null) {
int leftDp = treeDepth(root.left);
int rightDp = treeDepth(root.right);
dep = leftDp>=rightDp? leftDp+1:rightDp+1;
}
return dep;
} public void nodeCount(TreeNode root) {
if(root != null) {
cnt ++;
nodeCount(root.left);
nodeCount(root.right);
} } // Decodes your encoded data to tree.
public TreeNode deserialize(String data) { if(data == null) {
return null;
} Deque<String> queue = new LinkedList<String>();
Deque<TreeNode> nodeQueue = new LinkedList<TreeNode>();
String[] spData = data.split(" ");
int i = spData.length - 1;
while(spData[i].equals("null")) i--;
for(int j=0; j<=i; j++) {
queue.offer(spData[j]);
} TreeNode root = new TreeNode(Integer.parseInt(queue.poll())); nodeQueue.offer(root); while(!queue.isEmpty()) {
TreeNode p = nodeQueue.poll();
String lc = queue.peek();
if(!queue.isEmpty()) {
queue.poll();
if(lc != null) {
if(!lc.equals("null")) {
TreeNode node = new TreeNode(Integer.parseInt(lc));
p.left = node;
nodeQueue.offer(node);
}
} } if(!queue.isEmpty()) {
String rc = queue.peek();
queue.poll();
if(rc != null) {
if(!rc.equals("null")) {
TreeNode node = new TreeNode(Integer.parseInt(rc));
p.right = node;
nodeQueue.offer(node);
}
}
}
}
return root;
}
} // Your Codec object will be instantiated and called as such:
// Codec codec = new Codec();
// codec.deserialize(codec.serialize(root));

LeetCode——Serialize and Deserialize Binary Tree