LintCode-Serialization and Deserialization Of Binary Tree

Design an algorithm and write code to serialize and deserialize a binary tree. Writing the tree to a file is called 'serialization' and reading back from the file to reconstruct the exact same binary tree is 'deserialization'.

There is no limit of how you deserialize or serialize a binary tree, you only need to make sure you can serialize a binary tree to a string and deserialize this string to the original structure.

Example

An example of testdata: Binary tree {3,9,20,#,#,15,7},  denote the following structure:

    3
/ \
9 20
/ \
15 7

Our data serialization use bfs traversal. This is just for when you got wrong answer and want to debug the input.

You can use other method to do serializaiton and deserialization.

Solution:

 /**
* Definition of TreeNode:
* public class TreeNode {
* public int val;
* public TreeNode left, right;
* public TreeNode(int val) {
* this.val = val;
* this.left = this.right = null;
* }
* }
*/
class Solution {
/**
* This method will be invoked first, you should design your own algorithm
* to serialize a binary tree which denote by a root node to a string which
* can be easily deserialized by your own "deserialize" method later.
*/
public String serialize(TreeNode root) {
String res = "";
if (root==null) return res; List<TreeNode> nodeList = new ArrayList<TreeNode>();
nodeList.add(root);
int index = 0;
res = Integer.toString(nodeList.get(0).val);
while (index<nodeList.size()){
TreeNode cur = nodeList.get(index);
if (cur==null){
res += ",#,#";
} else {
if (cur.left!=null){
nodeList.add(cur.left);
res += ","+cur.left.val;
} else res += ",#";
if (cur.right!=null){
nodeList.add(cur.right);
res += ","+cur.right.val;
} else res += ",#";
}
index++;
} return res;
} /**
* This method will be invoked second, the argument data is what exactly
* you serialized at method "serialize", that means the data is not given by
* system, it's given by your own serialize method. So the format of data is
* designed by yourself, and deserialize it here as you serialize it in
* "serialize" method.
*/
public TreeNode deserialize(String data) {
if (data.isEmpty()) return null;
String[] temp = data.split(",");
TreeNode root = new TreeNode(Integer.parseInt(temp[0]));
List<TreeNode> nodeList = new ArrayList<TreeNode>();
nodeList.add(root);
int cur = 0, next = 1;
while (cur<nodeList.size()){
TreeNode curNode = nodeList.get(cur);
if (curNode==null) cur++;
else {
int left = next;
int right = next+1;
if (next<temp.length){
if (temp[next].equals("#")) nodeList.add(null);
else {
TreeNode leftChild = new TreeNode(Integer.parseInt(temp[next]));
curNode.left = leftChild;
nodeList.add(leftChild);
}
}
if (next+1<temp.length){
if (temp[next+1].equals("#")) nodeList.add(null);
else {
TreeNode rightChild = new TreeNode(Integer.parseInt(temp[next+1]));
curNode.right = rightChild;
nodeList.add(rightChild);
}
}
next += 2;
cur++;
}
} return root;
}
}
上一篇:修复wordpress插件编辑器漏洞


下一篇:vim中对文本的选择