/*
serialize 简单 层级遍历还是 前序遍历都没问题 需要注意的是每个数字后面加一个‘,’ 以便deserialize的时候好分离
deserialize 思路复杂,因为需要根据之前serialize的方式,来给出对应的解序列方法,层级遍历还用层级遍历解决,把每个root都存入q null也存,依次拿出 赋值对应的string【】里的数; 前序遍历用递归的方式怎么存就怎么取;在这里 serialize用 bfs实现 desirialize用递归实现
*/
/**
* 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.
public String serialize(TreeNode root) {
if(root == null) return new String("");
Stack<TreeNode> stack = new Stack<>();
StringBuilder sb = new StringBuilder();
stack.push(root);
while(!stack.isEmpty()) {
TreeNode temp = stack.pop();
if(temp == null) {
sb.append("#");
sb.append(",");
continue;
}
sb.append(temp.val);
sb.append(",");
stack.push(temp.right);
stack.push(temp.left);
}
sb.deleteCharAt(sb.length() - 1);
return sb.toString();
}
// Decodes your encoded data to tree.
public TreeNode deserialize(String data) {
if(data == null || data.length() == 0) return null;
String[] arr = data.split(",");
int[] num = new int[] {0};//这里用数组是为了方便 递归时饮用传递;
return helper(arr, num);
}
private TreeNode helper(String[] arr, int[] num) {
if(num[0] >= arr.length) return null;
if(arr[num[0]].equals("#")) return null;
TreeNode root = new TreeNode(Integer.valueOf(arr[num[0]]));
num[0] = num[0] + 1;
root.left = helper(arr, num);
num[0] = num[0] + 1;
root.right = helper(arr, num);
return root;
}
}
// Your Codec object will be instantiated and called as such:
// Codec codec = new Codec();
// codec.deserialize(codec.serialize(root));