Serialize and Deserialize Binary Tree
LeetCode 297 · கடினம் · தீர்வு, intuition & படிப்படியான வாக்த்ரூ
Level-order with null markers; rebuild with a parent queue.
நான் Serialize and Deserialize Binary Tree (LeetCode 297) ஐ இப்படித் தீர்த்தேன் — Construction / Serialization பேட்டர்னின் ஒரு கடினம் பிராப்ளம். கீழே: intuition, படிப்படியான approach, என் accepted Python கோட், animated test cases மற்றும் line-by-line debugger.
கீழேயுள்ள விளக்கம் ஆங்கிலத்தில் உள்ளது.
Intuition
Write the tree in level order with '#' for missing children — that's enough information to rebuild it. When reading it back, a queue of parents receives its left and right children two tokens at a time.
Approach
- 1
serialize: BFS, append value or '#', enqueue both children of real nodes.
- 2
deserialize: first token is the root; queue it.
- 3
For each parent from the queue, read the next two tokens as left and right.
- 4
Real children are queued as future parents.
நான் எப்படித் தீர்த்தேன்
Level-order codecPythonO(n) time · O(n) space
class Codec:
def serialize(self, root):
if root is None:
return ""
encodedString = ""
queue = [root]
while queue:
node = queue.pop(0)
if node is None:
encodedString += ",#" if encodedString else "#"
continue
encodedString += f",{node.val}" if encodedString else f"{node.val}"
queue.append(node.left)
queue.append(node.right)
return encodedString
def deserialize(self, data):
if data == "":
return None
nodes = data.split(",")
root = TreeNode(int(nodes[0]))
queue = [root]
i = 1
while i < len(nodes):
parent = queue.pop(0)
if nodes[i] != "#":
leftNode = TreeNode(int(nodes[i]))
parent.left = leftNode
queue.append(leftNode)
i += 1
if i < len(nodes) and nodes[i] != "#":
rightNode = TreeNode(int(nodes[i]))
parent.right = rightNode
queue.append(rightNode)
i += 1
return rootSerialize and Deserialize Binary Tree — அடிக்கடி கேட்கப்படும் கேள்விகள்
Serialize and Deserialize Binary Tree பின்னாலுள்ள intuition என்ன?
Write the tree in level order with '#' for missing children — that's enough information to rebuild it. When reading it back, a queue of parents receives its left and right children two tokens at a time.
Serialize and Deserialize Binary Tree (LeetCode 297) ஐ எப்படித் தீர்ப்பது?
1. serialize: BFS, append value or '#', enqueue both children of real nodes. 2. deserialize: first token is the root; queue it. 3. For each parent from the queue, read the next two tokens as left and right. 4. Real children are queued as future parents.
Serialize and Deserialize Binary Tree இன் time மற்றும் space complexity என்ன?
Time: O(n). Space: O(n). (Accepted approach: Level-order codec.)
Serialize and Deserialize Binary Tree இல் பொதுவான தவறுகள் என்ன?
Empty tree ↔ empty string. list.pop(0) is O(n); collections.deque makes each dequeue O(1) for big trees.