執行結果:
通過
顯示詳情
執行用時 :108 ms, 在所有 Java 提交中擊敗了21.70% 的用戶
內存消耗 :51.6 MB, 在所有 Java 提交中擊敗了5.10%的用戶
題目:
序列化是將一個數據結構或者對象轉換爲連續的比特位的操作,進而可以將轉換後的數據存儲在一個文件或者內存中,同時也可以通過網絡傳輸到另一個計算機環境,採取相反方式重構得到原數據。
請設計一個算法來實現二叉樹的序列化與反序列化。這裏不限定你的序列 / 反序列化算法執行邏輯,你只需要保證一個二叉樹可以被序列化爲一個字符串並且將這個字符串反序列化爲原始的樹結構。
示例:
你可以將以下二叉樹:
1
/ \
2 3
/ \
4 5
序列化爲 "[1,2,3,null,null,4,5]"
提示: 這與 LeetCode 目前使用的方式一致,詳情請參閱 LeetCode 序列化二叉樹的格式。你並非必須採取這種方式,你也可以採用其他的方法解決這個問題。
來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/serialize-and-deserialize-binary-tree
著作權歸領釦網絡所有。商業轉載請聯繫官方授權,非商業轉載請註明出處。
思路:
關鍵點一,採用前序遍歷進行序列化和反序列化
關鍵點二,格式值+空格+值,空節點用#代替
代碼:
/**
* 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.
String remainString;
public String serialize(TreeNode root) {
if(root==null)
{
return "#";
}
return root.val+" "+serialize(root.left)+" "+serialize(root.right);
}
// Decodes your encoded data to tree.
public TreeNode deserialize(String data) {
remainString=data;
return deserialize();
}
public TreeNode deserialize()
{
if(remainString==null)
{
return null;
}
int index=remainString.indexOf(" ");
String node=index==-1?remainString:remainString.substring(0,index);
remainString=index==-1?"":remainString.substring(index+1);
if(node.equals("#"))
{
return null;
}
int val=Integer.parseInt(node);
TreeNode root=new TreeNode(val);
root.left=deserialize();
root.right=deserialize();
return root;
}
}
// Your Codec object will be instantiated and called as such:
// Codec codec = new Codec();
// codec.deserialize(codec.serialize(root));