Skip to content

Bug Report for serialize-and-deserialize-binary-tree #3980

Open
@DezzardHD

Description

@DezzardHD

Bug Report for https://neetcode.io/problems/serialize-and-deserialize-binary-tree

Please describe the bug below and include any steps to reproduce the bug or screenshots if possible.
The following test case fails on leetcode but not on neetcode: [4,-7,-3,null,null,-9,-3,9,-7,-4,null,6,null,-6,-6,null,null,0,6,5,null,9,null,null,-1,-4,null,null,null,-2]

Broken code:

class Codec:
    
    # Encodes a tree to a single string.
    def serialize(self, root: Optional[TreeNode]) -> str:
        # preorder traversal
        res = ""
        def preorder(node):        
            nonlocal res
            if not node:
                res = res + "#"
                return
            res = res + "#" + str(node.val)
            preorder(node.left)
            preorder(node.right)
            return
        preorder(root)
        return res

    # Decodes your encoded data to tree.
    def deserialize(self, data: str) -> Optional[TreeNode]:
        arr = [None if not x else int(x) for x in data.split("#")]
        print(arr)
        def preorder_build(idx: int) -> (Optional[TreeNode], int):
            nonlocal arr
            if len(arr) <= idx or not arr[idx]:
                return None, idx + 1
            node = TreeNode(arr[idx])
            idx += 1
            node.left, idx = preorder_build(idx)
            node.right, idx = preorder_build(idx)
            return node, idx
        root, idx = preorder_build(1)
        return root

The test case includes a node value equal to zero.
My deserializer checked for not arr[idx] which is true for None and zero.
I intended to only check for None vaues.

Solution: Add the test case mentioned above to the test case collection of the question.

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