#297
Serialize and Deserialize Binary Tree
HardStringTreeDepth-First SearchBreadth-First SearchDesignBinary TreeTree TraversalRecursion
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
The optimal approach uses a pre-order traversal to serialize the tree into a string and utilizes an iterator to deserialize it back into the tree structure. This method is efficient and straightforward, leveraging the properties of tree traversal.
⚙️
Algorithm
3 steps- 1Step 1: Serialize the tree using pre-order traversal, appending values to a string with commas separating them.
- 2Step 2: For null nodes, append 'null' to indicate absence.
- 3Step 3: Deserialize by splitting the string and using an iterator to reconstruct the tree recursively.
solution.py25 lines
1# Full working Python code
2class TreeNode:
3 def __init__(self, val=0, left=None, right=None):
4 self.val = val
5 self.left = left
6 self.right = right
7
8class Codec:
9 def serialize(self, root):
10 def pre_order(node):
11 if not node:
12 return 'null'
13 return str(node.val) + ',' + pre_order(node.left) + ',' + pre_order(node.right)
14 return pre_order(root)
15
16 def deserialize(self, data):
17 def build_tree(values):
18 val = next(values)
19 if val == 'null':
20 return None
21 node = TreeNode(int(val))
22 node.left = build_tree(values)
23 node.right = build_tree(values)
24 return node
25 return build_tree(iter(data.split(',')))ℹ
Complexity note: The time complexity is O(n) because we visit each node exactly once during serialization and deserialization. The space complexity is O(n) due to the storage of the serialized string and the recursive call stack.
- 1Understanding tree traversal is crucial for serialization and deserialization.
- 2Using a queue or iterator can simplify the reconstruction process during deserialization.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.