Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

297. Serialize and Deserialize Binary Tree #90

Open
tech-cow opened this issue Feb 12, 2020 · 0 comments
Open

297. Serialize and Deserialize Binary Tree #90

tech-cow opened this issue Feb 12, 2020 · 0 comments

Comments

@tech-cow
Copy link
Owner

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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant