会递归遍历二叉树就会序列化。
package TreeTest;
import java.util.LinkedList;
import java.util.Queue;
/**
* @ProjectName: zxh0125
* @Package: TreeTest
* @ClassName: SerializeTree
* @Author: zxh
* @Description: 序列化二叉树
* @Date: 2022/1/24 12:09
* @Version: 1.0
*/
/*
* 前中后序序列号就只是换一下位置!
* */
public class SerializeTree {
public static Queue<String> preSerial(TreeNode head) {
Queue<String> ans = new LinkedList<>();
pres(head, ans);
return ans;
}
public static void pres(TreeNode head, Queue<String> ans) {
if (head == null) {
return;
}
ans.add(head.val + "");
pres(head.left, ans);
pres(head.right, ans);
}
public static TreeNode buildByPreQueue(Queue<String> ans) {
if (ans == null || ans.size() == 0) {
return null;
}
return preb(ans);
}
public static TreeNode preb(Queue<String> ans){
String value = ans.poll();
if(value == null){
return null;
}
TreeNode head = new TreeNode(Integer.parseInt(value));
head.left = preb(ans);
head.right = preb(ans);
return head;
}
}