Skip to content

297. Serialize and Deserialize Binary Tree #90

Description

@tech-cow

Try 2: Bug Free

from collections import deque
class Codec:
    def serialize(self, root):
        if not root: return ""
        res = []
        queue = deque([root])
        while queue:
            node = queue.popleft()
            if node:
                res.append(str(node.val))
                queue.append(node.left)
                queue.append(node.right)
            else:
                res.append("x")
        return ",".join(res)


    def deserialize(self, data):
        if not data: return None
        nums = data.split(",")
        root = TreeNode(nums[0])
        queue = deque([root])
        
        index = 0
        
        while queue:
            node = queue.popleft()
            index += 1
            if nums[index] != "x":
                node.left = TreeNode(int(nums[index]))
                queue.append(node.left)
            
            index += 1
            if nums[index] != "x":
                node.right = TreeNode(int(nums[index]))
                queue.append(node.right)
        return root

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions