|
| 1 | +# Time Complexity: |
| 2 | +# (1) serialize(): O(N) because traverse all nodes once. |
| 3 | +# (2) deserialize(): O(N) because process each node once. |
| 4 | + |
| 5 | +# Space Complexity: |
| 6 | +# (1) serialize(): O(N) to store the serialized string. |
| 7 | +# (2) deserialize(): O(N) for the queue and reconstructed tree. |
| 8 | + |
| 9 | +class Codec: |
| 10 | + def serialize(self, root): |
| 11 | + # store the tree as a list of values (BFS style) |
| 12 | + ans = [] |
| 13 | + if not root: |
| 14 | + return "" |
| 15 | + |
| 16 | + queue = [root] |
| 17 | + while queue: |
| 18 | + cur = queue.pop() |
| 19 | + if not cur: |
| 20 | + ans.append("n") # use 'n' to represent null nodes |
| 21 | + continue |
| 22 | + ans.append(str(cur.val)) # add node value as string |
| 23 | + queue.append(cur.right) # right first (for consistency in deserialization) |
| 24 | + queue.append(cur.left) # then left |
| 25 | + |
| 26 | + return ",".join(ans) # convert list to comma-separated string |
| 27 | + |
| 28 | + def deserialize(self, data): |
| 29 | + if not data: |
| 30 | + return None |
| 31 | + |
| 32 | + data = deque(data.split(",")) # convert string back to list |
| 33 | + root = TreeNode(int(data.popleft())) # first value is the root |
| 34 | + queue = [(root, 0)] # track parent nodes and child positions |
| 35 | + |
| 36 | + while data: |
| 37 | + if not queue: |
| 38 | + return None # should never happen unless input is corrupted |
| 39 | + |
| 40 | + cur = data.popleft() |
| 41 | + if cur == "n": |
| 42 | + val = None # null node, no need to create a TreeNode |
| 43 | + else: |
| 44 | + val = TreeNode(int(cur)) # create a new TreeNode |
| 45 | + |
| 46 | + parent, cnt = queue.pop() # get the parent and which child we’re setting |
| 47 | + if cnt == 0: |
| 48 | + parent.left = val # assign left child |
| 49 | + else: |
| 50 | + parent.right = val # assign right child |
| 51 | + |
| 52 | + cnt += 1 # move to the next child |
| 53 | + if cnt < 2: |
| 54 | + queue.append((parent, cnt)) # if parent still needs a right child, keep it in the queue |
| 55 | + if val: |
| 56 | + queue.append((val, 0)) # add new node to process its children later |
| 57 | + |
| 58 | + return root |
0 commit comments