Tree: Depth-First Search - Serialize and Deserialize Binary Tree
Given the following code snippet for serialization using BFS, what is the serialized string output for the binary tree below?
Tree:
1
/ \
2 3
/ \
4 null
from collections import deque
def serialize(root):
if not root:
return ''
queue = deque([root])
vals = []
while queue:
node = queue.popleft()
if node:
vals.append(str(node.val))
queue.append(node.left)
queue.append(node.right)
else:
vals.append('X')
while vals and vals[-1] == 'X':
vals.pop()
return ','.join(vals)
