Skip to content

Instantly share code, notes, and snippets.

@Semant1ka
Created January 18, 2022 02:57
Show Gist options
  • Select an option

  • Save Semant1ka/019b90162bb5e9e612a6beca82609697 to your computer and use it in GitHub Desktop.

Select an option

Save Semant1ka/019b90162bb5e9e612a6beca82609697 to your computer and use it in GitHub Desktop.

Revisions

  1. Semant1ka created this gist Jan 18, 2022.
    66 changes: 66 additions & 0 deletions solution.py
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,66 @@
    from collections import deque

    class Codec:

    def serialize(self, root):
    """Encodes a tree to a single string.
    :type root: TreeNode
    :rtype: str
    """
    if not root:
    return ""

    result = []
    q = deque([root])


    while(q):
    level_size = len(q)

    for _ in range(level_size):
    node = q.popleft()
    result.append(str(node.val) if node else "null")
    if node:
    q.append(node.left)
    q.append(node.right)

    return ",".join(result)



    def deserialize(self, data):
    """Decodes your encoded data to tree.
    :type data: str
    :rtype: TreeNode
    """
    if not data:
    return

    tree = data.split(",")
    root = TreeNode(val=int(tree[0]))
    # because we won't be able to count index if we start with zero
    # left = 2i
    # righ = 2i+1
    i=1

    q = deque([root])

    while(q):
    node = q.popleft()

    if node:
    left = tree[i]
    right = tree[i+1]

    node.left = None if left == 'null' else TreeNode(val=int(left))
    node.right = None if right == 'null' else TreeNode(val=int(right))

    q.append(node.left)
    q.append(node.right)

    i+=2

    return root