难度:困难
题目描述:
思路总结:终于又来了一道困难题,还是一样的酸爽,不过这题可以思路很简单的进行解决。
题解一:
pop(0)比较费时间,用iter——next,可以达到不错的效果,具体代码就不粘了,结果给一下。
# 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
"""
def predfs(node, res):
if not node:
res += "None,"
else:
res += str(node.val) +","
res = predfs(node.left, res)
res = predfs(node.right, res)
return res
return predfs(root, "")
def deserialize(self, data):
"""Decodes your encoded data to tree.
:type data: str
:rtype: TreeNode
"""
def helper(l):
if l[0] == "None":
l.pop(0)
return None
cur = TreeNode(l.pop(0))
cur.left = helper(l)
cur.right = helper(l)
return cur
data = data.split(",")
return helper(data)
#iter改进后的helper函数
def helper():
tmp = next(l)
if tmp == "None":
return None
cur = TreeNode(tmp)
cur.left = helper()
cur.right = helper()
return cur
# Your Codec object will be instantiated and called as such:
# codec = Codec()
# codec.deserialize(codec.serialize(root))