力扣 297. 二叉树的序列化

层序遍历树

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
# 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
"""
if not root: return "null"
# 层序遍历
ret, queue = [], [root]
while queue:
for _ in range(len(queue)):
cur = queue.pop(0)
if cur == None:
ret.append("null")
continue
ret.append(cur.val)
queue.append(cur.left)
queue.append(cur.right)
return " ".join(map(str, ret))


def deserialize(self, data):
"""Decodes your encoded data to tree.

:type data: str
:rtype: TreeNode
"""
# 层序构建树
data = data.split(" ")
if data[0] == "null":
return None
head = TreeNode(int(data[0]))
nodes = [head]
j = 1
for node in nodes:
if node != None:
node.left = TreeNode(int(data[j])) if data[j] != "null" else None
nodes.append(node.left)
j += 1
if j >= len(data):
return head
node.right = TreeNode(int(data[j])) if data[j] != "null" else None
nodes.append(node.right)
j += 1
if j >= len(data):
return head

  • Copyright: Copyright is owned by the author. For commercial reprints, please contact the author for authorization. For non-commercial reprints, please indicate the source.
  • Copyrights © 2022 eightyninth
  • Visitors: | Views:

请我喝杯咖啡吧~

支付宝
微信