Skip to content

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

@pranav1233

Description

@pranav1233

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

for the below code, I am able to submit my solution and it actually gets accepted. But there is a logical error in the deserialize section where I am not actually returning anything from the recursive function, but somehow I am able to "return root" which I haven't defined outside the recursive function. It should throw an error.

class Codec:

# Encodes a tree to a single string.
def serialize(self, root: Optional[TreeNode]) -> str:
    res=[]

    def dfs(node):
        if not node:
            res.append("N")
            return
        res.append(str(node.val))
        dfs(node.left)
        dfs(node.right)
    dfs(root)
    return ",".join(res)
    
# Decodes your encoded data to tree.
def deserialize(self, data: str) -> Optional[TreeNode]:
    val=data.split(",")
    i=0

    def dfs():
        nonlocal i
        if val[i] == "N":
            i+=1
            return None
        root=TreeNode(int(val[i]))
        i+=1
        root.left=dfs()
        root.right=dfs()
    dfs()

    return root
Image

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