-
Notifications
You must be signed in to change notification settings - Fork 0
Serialize and Deserialize Binary Tree
Tim_Gao edited this page Sep 15, 2016
·
5 revisions
- Use LinkedList as a global buffer
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Codec {
// Encodes a tree to a single string.
private void serialize(TreeNode n, StringBuilder sb){
if(n == null){
sb.append("null").append("#");
return;
}
sb.append(n.val).append("#");
serialize(n.left, sb);
serialize(n.right, sb);
}
public String serialize(TreeNode root) {
StringBuilder sb = new StringBuilder();
serialize(root, sb);
return sb.toString();
}
private TreeNode deserialize(LinkedList<String> strs){
String crt = strs.getFirst();
strs.removeFirst();
if (crt.equals("null")){
return null;
}
TreeNode n = new TreeNode(Integer.parseInt(crt));
n.left = deserialize(strs);
n.right = deserialize(strs);
return n;
}
// Decodes your encoded data to tree.
public TreeNode deserialize(String data) {
LinkedList<String> strs = new LinkedList<>(Arrays.asList(data.split("#")));
return deserialize(strs);
}
}
// Your Codec object will be instantiated and called as such:
// Codec codec = new Codec();
// codec.deserialize(codec.serialize(root));