Python – Serialize & Deserialize Binary Tree (DFS Pre‑Order) – Interview DSA Solution 🚀 #Serialize

preview_player
Показать описание
This solution addresses the Serialize and Deserialize Binary Tree problem using a DFS pre‑order traversal approach. The goal is to convert a binary tree into a string (serialization) and then rebuild the tree from the string (deserialization).

Key Concepts:

DFS Pre‑Order Traversal:
Visit the current node first, then recursively visit the left subtree followed by the right subtree.

Markers for Null:
Use a special marker (here, "#") to denote null nodes to preserve the tree structure.

Step‑by‑Step Explanation:

TreeNode Definition:
We define a simple binary tree node with a value and pointers to left and right children.

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

#BinaryTree #NodeStructure

Serialization (DFS):
The serialize method uses a helper function that performs a pre‑order traversal. For each node, it adds the node’s value to the result list; if a node is null, it appends the marker "#". The list is then joined into a single string.

def serialize(self, root):
def helper(node):
if not node:
return ['#']
return ' '.join(helper(root))

#PreOrder #TreeSerialization

Deserialization (DFS):
The deserialize method splits the serialized string into tokens and uses an iterator. A helper function reconstructs the tree by reading tokens in pre‑order; when a "#" is encountered, it returns None.

def deserialize(self, data):
def helper():
val = next(values)
if val == '#':
return None
node = TreeNode(int(val))
return node
return helper()
#TreeDeserialization #Recursion

Real‑World Applications:
This approach is frequently used in system design and data storage problems, where efficiently encoding and decoding tree structures is crucial.

Code:

# DFS Pre‑Order Approach for Serialize & Deserialize Binary Tree
class TreeNode:
def __init__(self, val=0, left=None, right=None):

class CodecDFS:
def serialize(self, root):
# Helper function using pre‑order traversal.
def helper(node):
if not node:
return ['#'] # Marker for None
# Pre‑order: node, left, right.
return ' '.join(helper(root))

def deserialize(self, data):
def helper():
val = next(values)
if val == '#':
return None
node = TreeNode(int(val))
return node
return helper()

# Example usage:
if __name__ == "__main__":
# Constructing a sample tree:
# 1
# / \
# 2 3
# / \
# 4 5
root = TreeNode(1, TreeNode(2), TreeNode(3, TreeNode(4), TreeNode(5)))
codec_dfs = CodecDFS()
print("DFS Serialized:", serialized)
# (Traverse deserialized_root to verify correctness)

#SerializeDeserialize #BinaryTree #DFS #PreOrder #CodingInterview
Рекомендации по теме
welcome to shbcf.ru