Leetcode 297. Serialize and Deserialize Binary Tree
题目链接: Serialize and Deserialize Binary Tree
难度:Hard
题目大意:
给出二叉树,将二叉树转出String,再从String中构建出二叉树。
思路:
参考高赞回答,利用递归思想,对二叉树采用前序遍历,各个节点之间用“,”分隔存储到StringBuilder中去,null用“#”表示。从String中恢复二叉树的时候,根据分隔符得到所有二叉树节点的值,然后恢复出二叉树。
代码
/**
* 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) {
StringBuilder sb=new StringBuilder();
return buildString(root,sb).toString();
}
private StringBuilder buildString(TreeNode root,StringBuilder s){
if(root==null){
return s.append("#").append(",");
}
else{//前序遍历
s.append(root.val).append(",");
buildString(root.left,s);
buildString(root.right,s);
return s;
}
}
// Decodes your encoded data to tree.
public TreeNode deserialize(String data) {
Queue<String> queue= new LinkedList<>(Arrays.asList(data.split(",")));
TreeNode root=buildTree(queue);
return root;
}
private TreeNode buildTree(Queue<String> queue){
String val=queue.poll();
if(val.equals("#")){
return null;
}
else{
TreeNode node=new TreeNode(Integer.parseInt(val));
node.left=buildTree(queue);
node.right=buildTree(queue);
return node;
}
}
}
// Your Codec object will be instantiated and called as such:
// Codec ser = new Codec();
// Codec deser = new Codec();
// TreeNode ans = deser.deserialize(ser.serialize(root));