#449
Serialize and Deserialize BST
MediumStringTreeDepth-First SearchBreadth-First SearchDesignBinary Search TreeBinary TreeTree TraversalRecursion
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(n) | O(n) |
💡
Intuition
Time O(n)Space O(n)
The optimal solution uses a pre-order traversal to serialize the tree while ensuring that the values are stored in a way that allows for efficient reconstruction of the BST. This method is both time-efficient and space-efficient.
⚙️
Algorithm
3 steps- 1Step 1: Use a pre-order traversal to serialize the tree into a string, including markers for null nodes.
- 2Step 2: Split the serialized string to retrieve values during deserialization.
- 3Step 3: Use a recursive function to rebuild the BST based on the pre-order sequence.
solution.py25 lines
1class TreeNode:
2 def __init__(self, val=0, left=None, right=None):
3 self.val = val
4 self.left = left
5 self.right = right
6
7class Codec:
8 def serialize(self, root):
9 def preorder(node):
10 if not node:
11 return 'null'
12 return str(node.val) + ',' + preorder(node.left) + ',' + preorder(node.right)
13 return preorder(root)
14
15 def deserialize(self, data):
16 values = data.split(',')
17 def build_bst():
18 val = values.pop(0)
19 if val == 'null':
20 return None
21 node = TreeNode(int(val))
22 node.left = build_bst()
23 node.right = build_bst()
24 return node
25 return build_bst()ℹ
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 recursion stack.
- 1Understanding pre-order traversal is crucial for serialization.
- 2Recognizing the importance of null markers in reconstruction.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.