public class Codec {
// Encodes a tree to a single string.
public String serialize(TreeNode root) {
if (root == null) return "";
StringBuilder sb = new StringBuilder();
Queue<TreeNode> q = new LinkedList<>();
q.add(root);
while (!q.isEmpty()) {
TreeNode node = q.poll();
if (node != null) {
q.add(node.left);
q.add(node.right);
sb.append(node.val).append(',');
} else sb.append("null,");
}
return sb.toString();
}
// Decodes your encoded data to tree.
public TreeNode deserialize(String data) {
if (data == null || data.length() == 0) return null;
String[] s = data.split(",");
int i = 1;
TreeNode root = new TreeNode(Integer.parseInt(s[0]));
Queue<TreeNode> q = new LinkedList<>();
q.add(root);
while (!q.isEmpty()) {
TreeNode node = q.poll();
if (!"null".equals(s[i])) {
TreeNode l = new TreeNode(Integer.parseInt(s[i]));
node.left = l;
q.add(l);
}
i++;
if (!"null".equals(s[i])) {
TreeNode r = new TreeNode(Integer.parseInt(s[i]));
node.right = r;
q.add(r);
}
i++;
}
return root;
}
}
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string.
:type root: TreeNode
:rtype: str
"""
queue = [root]
ls = []
while queue != []:
cur = queue[0]
if cur!= None and cur.left:
queue.append(cur.left)
if cur!= None and not cur.left:
queue.append(None)
if cur!= None and cur.right:
queue.append(cur.right)
if cur !=None and not cur.right:
queue.append(None)
if cur != None:
ls.append(str(cur.val))
else:
ls.append("None")
queue = queue[1:]
st = ",".join(ls)
return st
def deserialize(self, data):
"""Decodes your encoded data to tree.
:type data: str
:rtype: TreeNode
"""
if data == "None":
return None
ls = data.split(",")
root = TreeNode(int(ls[0]))
queue = [root]
i = 1
while queue != []:
cur = queue[0]
# 建立左节点
if ls[i] != "None":
# 记得这里只能new 一个对象,同时用于建立子节点和list添加
left = TreeNode(int(ls[i]))
cur.left = left
queue.append(left)
i += 1
# 建立右节点
if ls[i] != "None":
right = TreeNode(int(ls[i]))
cur.right = right
queue.append(right)
i += 1
queue = queue[1:]
return root
public class Codec {
//广度遍历
// Encodes a tree to a single string.
public String serialize(TreeNode root) {
if (root == null) {
return "";
}
StringBuilder build = new StringBuilder();
Queue<TreeNode> queue = new LinkedList<>();
queue.add(root);
while (!queue.isEmpty()) {
TreeNode t = queue.poll();
if (t != null) {
queue.add(t.left);
queue.add(t.right);
build.append(t.val + ",");
} else {
build.append("null,");
}
}
return build.toString();
}
// Decodes your encoded data to tree.
public TreeNode deserialize(String data) {
if (data == null || data.length() <= 0)
return null;
String[] s = data.split(",");
Queue<TreeNode> queue = new LinkedList<>();
TreeNode root = new TreeNode(Integer.parseInt(s[0]));
queue.add(root);
int i = 1;
while (!queue.isEmpty()) {
TreeNode t = queue.poll();
//构建左节点
if (!s[i].equals("null")) {
TreeNode left = new TreeNode(Integer.parseInt(s[i]));
t.left = left;
queue.add(left);
}
i++;
if (!s[i].equals("null")) {
TreeNode right = new TreeNode(Integer.parseInt(s[i]));
t.right = right;
queue.add(right);
}
i++;
}
return root;
}
}
public class Codec {
// Encodes a tree to a single string.
public String serialize(TreeNode root) {
if(root == null) return "";
StringBuilder build = new StringBuilder();
Queue<TreeNode> queue = new LinkedList<>();
queue.add(root);
while(!queue.isEmpty()){
TreeNode no = queue.poll();
if(no != null){
queue.add(no.left);
queue.add(no.right);
build.append(no.val+",");
}else{
build.append("null,");
}
}
return build.toString();
}
// Decodes your encoded data to tree.
public TreeNode deserialize(String data) {
if(data ==null || data.length()<= 0){
return null;
}
String[] s = data.split(",");
Queue<TreeNode> queue = new LinkedList<>();
TreeNode root = new TreeNode(Integer.parseInt(s[0]));
queue.add(root);
int i = 1;
while(!queue.isEmpty()){
TreeNode t = queue.poll();
//构建左节点
if(!s[i].equals("null")){
TreeNode left = new TreeNode(Integer.parseInt(s[i]));
t.left = left;
queue.add(left);
}
i++;
//构建右节点
if(!s[i].equals("null")){
TreeNode right = new TreeNode(Integer.parseInt(s[i]));
t.right =right;
queue.add(right);
}
i++;
}
return root;
}
}
public class Codec {
// Encodes a tree to a single string.
public String serialize(TreeNode root) {
if (root == null) {
return "";
}
StringBuilder res = new StringBuilder();
Queue<TreeNode> queue = new LinkedList<>();
queue.add(root);
while (!queue.isEmpty()) {
TreeNode node = queue.poll();
if (node != null) {
queue.add(node.left);
queue.add(node.right);
res.append(node.val + " ");
} else {
res.append("null ");
}
}
return res.toString();
}
// Decodes your encoded data to tree.
public TreeNode deserialize(String data) {
if (data == "") {
return null;
}
String[] nums = data.split(" ");
// 构建根节点root
TreeNode root = new TreeNode(Integer.valueOf(nums[0]));
Queue<TreeNode> queue = new LinkedList<>();
queue.add(root);
int i = 0;
while (!queue.isEmpty()) {
TreeNode node = queue.poll();
i ++;
if (!nums[i].equals("null")) {
TreeNode leftNode = new TreeNode(Integer.valueOf(nums[i]));
queue.add(leftNode);
node.left = leftNode;
}
i ++;
if (!nums[i].equals("null")) {
TreeNode rightNode = new TreeNode(Integer.valueOf(nums[i]));
queue.add(rightNode);
node.right = rightNode;
}
}
return root;
}
}
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string.
:type root: TreeNode
:rtype: str
"""
queue1=collections.deque()
queue2=collections.deque()
if root:
queue1.append(root)
else:
return
while queue1:
node=queue1.popleft()
if node:
queue1.append(node.left)
queue1.append(node.right)
queue2.append(node)
return queue2 # 按理来说,这里应当是返回一个str类型且末尾的none是需要去掉的,但是这里取巧了
def deserialize(self, data):
"""Decodes your encoded data to tree.
:type data: str # 因为是自己调用的,所以这里直接上一步用的deque的返回值,这里使用的是deque作为传入的参数
:rtype: TreeNode
"""
# 思路:采用一个递归的方式,已经通过数学方式推导知道了在序列化的这种情况下parent节点与左右孩子节点的index关系
# 设 parent在data中的index是 n,设前面含有m个none节点,则在起始index为0的情况下,左孩子的index是 2(n-m)+1,右孩子的index是 2(n-m)+2
# 序列data作为外部变量直接调用,,现在的问题是,难道每个节点都要遍历一次前面有多少个none吗?我们应该在外部遍历一遍,把这个信息整体存下来
if not data:
return
num=0
numOfNone=[]
for x in data:
if not x:
num+=1
numOfNone.append(num) # 用于存储每个节点下标前面有多少个none在queue/data中
length=len(data)-1
def dfs(i):
nonlocal data,numOfNone
if i>length or (not data[i]):
return
root=TreeNode(data[i].val)
root.left=dfs(2*(i-numOfNone[i])+1)
root.right=dfs(2*(i-numOfNone[i])+2)
return root
return dfs(0)
# Your Codec object will be instantiated and called as such:
# codec = Codec()
# codec.deserialize(codec.serialize(root))
大神解法 手动狗头
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string.
:type root: TreeNode
:rtype: str
"""
return root
def deserialize(self, data):
"""Decodes your encoded data to tree.
:type data: str
:rtype: TreeNode
"""
return data
# Your Codec object will be instantiated and called as such:
# codec = Codec()
# codec.deserialize(codec.serialize(root))
public class Codec {
//广度遍历
// Encodes a tree to a single string.
public String serialize(TreeNode root) {
//序列化成字符串1,2,3,null,null,4,5,null...
if (root == null) {
return "";
}
StringBuilder build = new StringBuilder();
Queue<TreeNode> queue = new LinkedList<>();
queue.add(root);
while (!queue.isEmpty()) {
TreeNode t = queue.poll();
if (t != null) {
queue.add(t.left);
queue.add(t.right);
build.append(t.val + ",");
} else {
build.append("null,");
}
}
return build.toString();
}
// Decodes your encoded data to tree.
public TreeNode deserialize(String data) {
if (data == null || data.length() <= 0)
return null;
String[] s = data.split(",");
Queue<TreeNode> queue = new LinkedList<>();
TreeNode root = new TreeNode(Integer.parseInt(s[0]));
queue.add(root);
int i = 1;
while (!queue.isEmpty()) {
TreeNode t = queue.poll();
//构建左节点
if (!s[i].equals("null")) {
TreeNode left = new TreeNode(Integer.parseInt(s[i]));
t.left = left;
queue.add(left);
}
i++;
if (!s[i].equals("null")) {
TreeNode right = new TreeNode(Integer.parseInt(s[i]));
t.right = right;
queue.add(right);
}
i++;
}
return root;
}
}
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
//序列化
public class Codec {
private TreeNode root;
// Encodes a tree to a single string.
public String serialize(TreeNode root) {
// //
// this.root = root;
// return null;
if (root == null) {
return null;
}
StringBuilder sb = new StringBuilder();
Queue<TreeNode> queue = new LinkedList<>();
queue.add(root);
while (!queue.isEmpty()) {
TreeNode t = queue.poll();
if (t != null) {
queue.add(t.left);
queue.add(t.right);
sb.append(t.val + ",");
} else {
sb.append("null,");
}
}
return sb.toString();
}
// Decodes your encoded data to tree.
public TreeNode deserialize(String data) {
if (data == null || data.length() <= 0) {
return null;
}
String[] s = data.split(",");
Queue<TreeNode> queue = new LinkedList<>();
queue.add(root);
int i = 1;
while (!queue.isEmpty()) {
TreeNode t = queue.poll();
if (!s[i].equals("null")) {
TreeNode t1 = new TreeNode(Integer.parseInt(s[i]));
t1.left = t1;
queue.add(t1);
}
i++;
if (!s[i].equals("null")) {
TreeNode t1 = new TreeNode(Integer.parseInt(s[i]));
t1.right = t1;
queue.add(t1);
}
i++;
}
return root;
}
}
// Your Codec object will be instantiated and called as such:
// Codec codec = new Codec();
// codec.deserialize(codec.serialize(root));
/**
* 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) {
if(root==null) return "";
Queue<TreeNode> queue = new LinkedList<>();
StringBuilder sb = new StringBuilder();
queue.add(root);
while(!queue.isEmpty()){
TreeNode node = queue.poll();
if(node!=null){
queue.add(node.left);
queue.add(node.right);
sb.append(node.val+",");
}else{
sb.append("null,");
}
}
return sb.toString();
}
// Decodes your encoded data to tree.
public TreeNode deserialize(String data) {
if(data == null || data.length()==0){
return null;
}
String[] s = data.split(",");
Queue<TreeNode> queue = new LinkedList<>();
TreeNode root = new TreeNode(Integer.parseInt(s[0]));
queue.add(root);
int i = 1;
while(!queue.isEmpty()){
TreeNode t = queue.poll();
if(!s[i].equals("null")){
TreeNode t1 = new TreeNode(Integer.parseInt(s[i]));
t.left = t1;
queue.add(t1);
}
i++;
if(!s[i].equals("null")){
TreeNode t1 = new TreeNode(Integer.parseInt(s[i]));
t.right = t1;
queue.add(t1);
}
i++;
}
return root;
}
}
// Your Codec object will be instantiated and called as such:
// Codec codec = new Codec();
// codec.deserialize(codec.serialize(root));
/**
* 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) {
if (root == null) {
return "";
}
StringBuilder build = new StringBuilder();
Queue<TreeNode> queue = new LinkedList<>();
queue.add(root);
while (!queue.isEmpty()) {
TreeNode t = queue.poll();
if (t != null) {
queue.add(t.left);
queue.add(t.right);
build.append(t.val + ",");
} else {
build.append("null,");
}
}
return build.toString();
}
// Decodes your encoded data to tree.
public TreeNode deserialize(String data) {
if (data == null || data.length() <= 0) {
return null;
}
String[] s = data.split(",");
Queue<TreeNode> queue = new LinkedList<>();
TreeNode root = new TreeNode(Integer.parseInt(s[0]));
queue.add(root);
int i = 1;
while (!queue.isEmpty()) {
TreeNode t = queue.poll();
if (!s[i].equals("null")) {
TreeNode left = new TreeNode(Integer.parseInt(s[i]));
t.left = left;
queue.add(left);
}
i++;
if (!s[i].equals("null")) {
TreeNode right = new TreeNode(Integer.parseInt(s[i]));
t.right = right;
queue.add(right);
}
i++;
}
return root;
}
}
// Your Codec object will be instantiated and called as such:
// Codec codec = new Codec();
// codec.deserialize(codec.serialize(root));
/**
使用#代替null,当遇到#说明此处无节点
*/
public class Codec {
//[1,2,3,null,null,4,5];
// Encodes a tree to a single string.
public String serialize(TreeNode root) {
StringBuilder sb = new StringBuilder();
if(root == null) return "";
LinkedList<TreeNode> queue = new LinkedList<>();
queue.push(root);
while(!queue.isEmpty()){
TreeNode cur = queue.removeFirst();
if(cur != null){
queue.addLast(cur.left);
queue.addLast(cur.right);
sb.append(cur.val);
}else{
sb.append("#");
}
}
//此时得到的是123##45##;需要去除最后的##,长度为1+2+3+4..(height+1)*height/2
// return sb.substring(0,(height+1)*height/2+1).toString();
return sb.toString();
}
// Decodes your encoded data to tree.
public TreeNode deserialize(String data) {
if(data == null || data.length() <= 0) return null;
//得到123##45
char[] c = data.toCharArray();
LinkedList<TreeNode> queue = new LinkedList<>();
TreeNode root = new TreeNode(c[0]-'0');
TreeNode tmp = root;
queue.addLast(tmp);
int i = 1;
while(!queue.isEmpty()){
TreeNode cur = queue.removeFirst();
if(c[i] != '#'){
TreeNode left = new TreeNode(c[i]-'0');
cur.left = left;
queue.addLast(left);
}
i++;
if(c[i]!= '#'){
TreeNode right = new TreeNode(c[i]-'0');
cur.right = right;
queue.addLast(right);
}
i++;
}
return root;
}
}
// Your Codec object will be instantiated and called as such:
// Codec codec = new Codec();
// codec.deserialize(codec.serialize(root));
改后->判断单位为String,避免正负号的问题。使用split
序列化时间复杂度O(N) 空间复杂度O(N)
反序列化时间复杂度O(N) 空间复杂度O(N)
/**
使用#代替null,当遇到#说明此处无节点
*/
public class Codec {
//[1,2,3,null,null,4,5];
// Encodes a tree to a single string.
public String serialize(TreeNode root) {
StringBuilder sb = new StringBuilder();
if(root == null) return "";
LinkedList<TreeNode> queue = new LinkedList<>();
queue.push(root);
while(!queue.isEmpty()){
TreeNode cur = queue.removeFirst();
if(cur != null){
queue.addLast(cur.left);
queue.addLast(cur.right);
sb.append(cur.val+",");
}else{
sb.append("#,");
}
}
//此时得到的是123##45##;需要去除最后的##,长度为1+2+3+4..(height+1)*height/2
// return sb.substring(0,(height+1)*height/2+1).toString();
return sb.toString();
}
// Decodes your encoded data to tree.
public TreeNode deserialize(String data) {
if(data == null || data.length() <= 0) return null;
//得到123##45
String[] c = data.split(",");
LinkedList<TreeNode> queue = new LinkedList<>();
TreeNode root = new TreeNode(Integer.parseInt(c[0]));
TreeNode tmp = root;
queue.addLast(tmp);
int i = 1;
while(!queue.isEmpty()){
TreeNode cur = queue.removeFirst();
if(!c[i].equals("#")){
TreeNode left = new TreeNode(Integer.parseInt(c[i]));
cur.left = left;
queue.addLast(left);
}
i++;
if(!c[i].equals("#")){
TreeNode right = new TreeNode(Integer.parseInt(c[i]));
cur.right = right;
queue.addLast(right);
}
i++;
}
return root;
}
}
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string.
:type root: TreeNode
:rtype: str
"""
if not root : return root
res,num= [],[root]
while num:
k = num.pop(0)
if k:
res.append(str(k.val)+",")
num.append(k.left)
num.append(k.right)
else:
res.append("n,")
return ''.join(res)
def deserialize(self, data):
"""Decodes your encoded data to tree.
:type data: str
:rtype: TreeNode
"""
if not data:return []
res = data.split(",")
root = TreeNode(res[0])
num ,i= [root],1
while num:
k = num.pop(0)
if res[i]!= "n":
k.left = TreeNode(res[i])
num.append(k.left)
i+=1
if res[i] != "n":
k.right = TreeNode(res[i])
num.append(k.right)
i+=1
return root
共以下 25 个回答
BFS
解题思路:使用层序遍历思想,序列化时,记录当前节点值,子节点为None时,也进行保存,反序列化时,将不为None得数构造成节点并放入队列,循环队列不为空的情况,弹出节点作为当前节点,下一个不为None的节点作为左节点,在下一个不为None的节点作为右节点。
时间复杂度:O(n)
空间复杂度:O(n)
思路:序列化成一个字符串,反序列化时要能够确定每一个节点的左右子节点。
实现方式一:层序遍历,BFS。序列化时需要遍历每一个节点,需要一个队列实现层序遍历。还要算上空节点。时间和空间复杂度都为O(N),反序列化时的时间和空间复杂度也都为O(N)。
实现方式二:前序遍历,dfs。都会访问树中所有节点一次,递归会使用栈空间。所以序列化和反序列化的时间和空间的复杂度都为O(N)。
垃圾解法:
大神解法 手动狗头
//层序遍历
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Codec {
public:
};
// Your Codec object will be instantiated and called as such:
// Codec codec;
// codec.deserialize(codec.serialize(root));
时间空间复杂度都为O(n)
前序遍历,时间O(n),空间O(n)
根据层序遍历顺序打印
时间O(n)
空间O(n)
使用层序遍历进行序列化,注意需要对最后的几个null进行处理使输出符合该题的输出规范
时间:O(n),空间:O(n)
自己写了一遍,没有通过主要问题如下
改后->判断单位为String,避免正负号的问题。使用split
序列化时间复杂度O(N) 空间复杂度O(N)
反序列化时间复杂度O(N) 空间复杂度O(N)
前序
第一个想法比较暴力,是用模版遍历前序和中序,然后在反序列化函数中,分割出来前序数组和中序数组,用前几天出的前序和中序题的模版合成链表的方法。
然后是题解的解法,用层次遍历,刚开始我用层次处理不了有子节点为None的情况,然后题解使用if去判断解决这个问题,反序列化和序列化算法差不多,无非是res存储的不同。 时间复杂度O(n),空间复杂度O(n)
第一个想法行不通,因为前几天做的那些是没有重复元素的,这道题的测试用例有重复数据的。