请实现两个函数,分别用来序列化和反序列化二叉树
利用广度遍历实现二叉树的序列化和非序列化。
核心思想:广度遍历
import java.util.*;
public class Solution {
String Serialize(TreeNode root) {
if(root == null) return "#,";
StringBuilder builder = new StringBuilder();
Queue<TreeNode> queue = new LinkedList<>();
queue.offer(root);
while(!queue.isEmpty()){
TreeNode node = queue.poll();
if(node != null) {
builder.append(node.val + ",");
queue.offer(node.left);
queue.offer(node.right);
}
else builder.append("#,");
}
return builder.toString();
}
TreeNode Deserialize(String str) {
String[] strs = str.split(",");
if(str.equals("") || strs[0].equals("#")) return null;
TreeNode root = new TreeNode(Integer.valueOf(strs[0]));
Queue<TreeNode> queue = new LinkedList<>();
queue.offer(root);
for(int i=1;i<strs.length;i++){
TreeNode node = queue.poll();
if(!strs[i].equals("#")){
TreeNode left = new TreeNode(Integer.valueOf(strs[i]));
node.left = left;
queue.offer(left);
}
if(!strs[++i].equals("#")){
TreeNode right = new TreeNode(Integer.valueOf(strs[i]));
node.right = right;
queue.offer(right);
}
}
return root;
}
}
网友评论