#297
Serialize and Deserialize Binary Tree
hard· Treesruns: 0Serialization is the process of converting a data structure into a sequence of bits so that it can be stored or transmitted, and reconstructed later. Design an algorithm to serialize and deserialize a binary tree. You may pick any string format you like.
sign in to paste and practice your own solution
wpm 0acc 100%time 0:000 / 790
class Codec:
def serialize(self, root: TreeNode | None) -> str:
result = []
def dfs(node: TreeNode | None) -> None:
if not node:
result.append("N")
return
result.append(str(node.val))
dfs(node.left)
dfs(node.right)
dfs(root)
return ",".join(result)
def deserialize(self, data: str) -> TreeNode | None:
values = data.split(",")
self.i = 0
def dfs() -> TreeNode | None:
if values[self.i] == "N":
self.i += 1
return None
node = TreeNode(int(values[self.i]))
self.i += 1
node.left = dfs()
node.right = dfs()
return node
return dfs()
click the box to focus · tab inserts 4 spaces · backspace to correct · esc to pause
desktop only
codedrill is a typing game and needs a real keyboard. open this on a laptop or desktop to practice.
you can still browse problems and sections from your phone.