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
Projects

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
@tech-cow tech-cow created this issue from a note in Facebook (Weekend Oversee) Feb 12, 2020
@tech-cow tech-cow moved this from Weekend Oversee to 二刷 | 三刷 in Facebook Mar 19, 2020
@tech-cow tech-cow moved this from 二刷 | 三刷 to 重刷 in Facebook Mar 19, 2020
@tech-cow tech-cow moved this from 重刷 to 二刷 | 三刷 in Facebook Mar 19, 2020
@tech-cow tech-cow moved this from 二刷 | 三刷 to Bug-free / Completed in Facebook Jun 18, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
Facebook
  
Bug-free / Completed
Development

No branches or pull requests

1 participant