中级农民
- 积分
- 102
- 大米
- 颗
- 鳄梨
- 个
- 水井
- 尺
- 蓝莓
- 颗
- 萝卜
- 根
- 小米
- 粒
- 学分
- 个
- 注册时间
- 2013-3-3
- 最后登录
- 1970-1-1
|
依我来看,给出的应该不是一随意的乱序,而是一个BST的先根序遍历。所以还是照搬449的做法。
- 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
- """
- R = []
- L = [root]
- def DFS(node):
- if node:
- R.append(node.val)
- DFS(node.left)
- DFS(node.right)
- DFS(root)
- return R
- def deserialize(self, data):
- """Decodes your encoded data to tree.
- :type data: str
- :rtype: TreeNode
- """
- def BuildTree(start, end):
- if start >= end:
- return None
- i = start + 1
- while i < end and data[i] < data[start]:
- i += 1
- root = TreeNode(data[start])
- root.left = BuildTree(start + 1, i)
- root.right = BuildTree(i, end)
- return root
- return BuildTree(0, len(data))
复制代码 |
|