-
Notifications
You must be signed in to change notification settings - Fork 17
/
serialize-and-deserialize-bst.py
77 lines (58 loc) · 1.88 KB
/
serialize-and-deserialize-bst.py
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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
from typing import List, Tuple, Deque, Optional
from collections import deque
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x: int) -> None:
self.val = x
self.left: Optional[TreeNode] = None
self.right: Optional[TreeNode] = None
class Codec:
def serialize(self, root: TreeNode) -> str:
"""Encodes a tree to a single string.
"""
queue: Deque[TreeNode] = deque()
if root:
queue.append(root)
result: List[str] = []
while queue:
node = queue.popleft()
result.append(str(node.val))
if node.left:
queue.append(node.left)
if node.right:
queue.append(node.right)
return ",".join(result)
def deserialize(self, data: str) -> Optional[TreeNode]:
"""Decodes your encoded data to tree.
"""
def tree_insert(
root: Optional[TreeNode], new_node: TreeNode
) -> Optional[TreeNode]:
node = root
parent = None
while node:
parent = node
if node.val < new_node.val:
node = node.right
else:
node = node.left
if not parent:
root = new_node
elif parent.val > new_node.val:
parent.left = new_node
else:
parent.right = new_node
return root
if not data:
return None
root = None
for val_str in data.split(","):
root = tree_insert(root, TreeNode(int(val_str)))
return root
# Your Codec object will be instantiated and called as such:
# Your Codec object will be instantiated and called as such:
# ser = Codec()
# deser = Codec()
# tree = ser.serialize(root)
# ans = deser.deserialize(tree)
# return ans