* Definition for a binary tree node.
* public class TreeNode {
* TreeNode(int x) { val = x; }
// Encodes a tree to a single string.
public String serialize(TreeNode root) {
StringBuilder res = new StringBuilder();
convertToString(root, res);
public void convertToString(TreeNode node, StringBuilder res) {
res.append("#").append(",");
res.append(node.val).append(",");
convertToString(node.left, res);
convertToString(node.right, res);
// Decodes your encoded data to tree.
public TreeNode deserialize(String data) {
Queue<String> queue = new LinkedList<>();
queue.addAll(Arrays.asList(data.split(",")));
public TreeNode buildTree(Queue<String> queue) {
String val = queue.remove();
TreeNode node = new TreeNode(Integer.valueOf(val));
node.left = buildTree(queue);
node.right = buildTree(queue);
// Your Codec object will be instantiated and called as such:
// Codec codec = new Codec();
// codec.deserialize(codec.serialize(root));