Skip to content

Commit 7402dd6

Browse files
committed
solve(w12): 297. Serialize and Deserialize Binary Tree
1 parent 62f8abf commit 7402dd6

File tree

1 file changed

+64
-0
lines changed

1 file changed

+64
-0
lines changed
Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
# https://leetcode.com/problems/serialize-and-deserialize-binary-tree/
2+
3+
# Definition for a binary tree node.
4+
class TreeNode(object):
5+
def __init__(self, x):
6+
self.val = x
7+
self.left = None
8+
self.right = None
9+
10+
class Codec:
11+
12+
def serialize(self, root):
13+
"""Encodes a tree to a single string.
14+
15+
:type root: TreeNode
16+
:rtype: str
17+
"""
18+
res = []
19+
20+
def preorder_ser(node):
21+
# base condition
22+
if not node:
23+
res.append("None")
24+
return
25+
26+
# traversal
27+
res.append(str(node.val))
28+
preorder_ser(node.left)
29+
preorder_ser(node.right)
30+
31+
preorder_ser(root)
32+
33+
return ",".join(res)
34+
35+
def deserialize(self, data):
36+
"""Decodes your encoded data to tree.
37+
38+
:type data: str
39+
:rtype: TreeNode
40+
"""
41+
from collections import deque
42+
43+
preorder_vals = deque(data.split(","))
44+
45+
def preorder_deser():
46+
val = preorder_vals.popleft()
47+
48+
# base condition
49+
if val == "None":
50+
return None
51+
52+
# traversal
53+
node = TreeNode(int(val))
54+
node.left = preorder_deser()
55+
node.right = preorder_deser()
56+
57+
return node
58+
59+
return preorder_deser()
60+
61+
# Your Codec object will be instantiated and called as such:
62+
# ser = Codec()
63+
# deser = Codec()
64+
# ans = deser.deserialize(ser.serialize(root))

0 commit comments

Comments
 (0)