题目描述:
请实现两个函数,分别用来序列化和反序列化二叉树
解题思路:
使用先序遍历方法遍历序列化二叉树,如果某一个节点为null,则使用#代替,反序列化时同样是按照先序的的顺序来不断解析出根节点的左右子树。
代码(java):
/*
public class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;
public TreeNode(int val) {
this.val = val;
}
}
*/
import java.util.*;
public class Solution {
String Serialize(TreeNode root) {
if(root==null)return "#,";
StringBuffer res=new StringBuffer(root.val + ",");
res.append(Serialize(root.left));
res.append(Serialize(root.right));
return res.toString();
}
TreeNode Deserialize(String str) {
String []strSplit=str.split(",");
Queue<String> queue=new LinkedList<String>();
for(int i=0;i<strSplit.length;i++){
queue.offer(strSplit[i]);
}
return pre(queue);
}
TreeNode pre(Queue<String> queue){
String s=queue.poll();
if(s.equals("#")){
return null;
}
TreeNode root=new TreeNode(Integer.parseInt(s));
root.left=pre(queue);
root.right=pre(queue);
return root;
}
}