Coding Hard Software Engineer Backend Full Stack

Serialize and deserialize a binary tree to and from a string.

Practise this question with AI feedback

Record your spoken answer or type your response to receive immediate scoring and STAR improvements.

💡 Suggested Approach & Sample Answer

Optimal Pre-order Traversal (DFS) Approach:
- Serialize nodes in pre-order with commas, recording null children as markers ('#'). Deserialization reconstructs the tree recursively consuming tokens.

class TreeNode:
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right

class Codec:
def serialize(self, root: TreeNode) -> str:
res = []
def dfs(node):
if not node:
res.append('#')
return
res.append(str(node.val))
dfs(node.left)
dfs(node.right)
dfs(root)
return ','.join(res)

def deserialize(self, data: str) -> TreeNode:
vals = iter(data.split(','))
def build():
val = next(vals)
if val == '#':
return None
node = TreeNode(int(val))
node.left = build()
node.right = build()
return node
return build()

Complexity & Key Logic:
- Time Complexity: O(N) for both serialize and deserialize.
- Space Complexity: O(N) for output string and recursion stack.
- Algorithm Details:
- Using explicit null markers preserves tree topology unambiguously during pre-order rebuild.

🎯 What Interviewers Listen For

How would you answer this in a real interview?

Use our free AI mock practice tool to test your response, analyze speaking pacing, and refine your STAR structure.

🔗 Related Coding Questions