/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ publicclassCodec {
// Encodes a tree to a single string. public String serialize(TreeNode root) { if (root == null) { return""; } StringBuildersb=newStringBuilder(); dfs(root, sb); return sb.toString(); }
// Decodes your encoded data to tree. public TreeNode deserialize(String data) { if (data.length() == 0) { returnnull; } String[] ss = data.split(","); Queue<String> queue = newLinkedList<>(); for (String s : ss) { queue.offer(s); } return dfs(queue); }