Skip to content

[BUG] - Error in code in approach 5 implementation #30118

@rajansandeep

Description

@rajansandeep

LeetCode Username

blacksoul1123

Problem Number, Title, and Link

https://leetcode.com/problems/closest-binary-search-tree-value-ii/

Bug Category

Editorial

Bug Description

Approach 5 implementation has an error for return type.

TypeError: deque([3, 4]) is not valid value for the expected return type list
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
raise TypeError(str(ret) + " is not valid value for the expected return type list");
Line 61 in _driver (Solution.py)
_driver()
Line 70 in (Solution.py)
During handling of the above exception, another exception occurred:
TypeError: Type is not JSON serializable: collections.deque
Line 203 in _serialize (./python3/serializer.py)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
out = ser._serialize(ret, 'list')
Line 59 in _driver (Solution.py)

Language Used for Code

Python/Python3

Code used for Submit/Run operation

class Solution:
    def closestKValues(self, root: TreeNode, target: float, k: int) -> List[int]:
        def dfs(node, queue):
            if not node:
                return
            
            dfs(node.left, queue)
            queue.append(node.val)
            if len(queue) > k:
                if (abs(target - queue[0]) <= abs(target - queue[-1])):
                    queue.pop()
                    return
                else:
                    queue.popleft()
                    
            dfs(node.right, queue)
        
        queue = deque()
        dfs(root, queue)
        return queue

Expected behavior

Tests passing

Screenshots

No response

Additional context

The tests pass by wrapping the return type with list

class Solution:
    def closestKValues(self, root: TreeNode, target: float, k: int) -> List[int]:
        def dfs(node, queue):
            if not node:
                return
            
            dfs(node.left, queue)
            queue.append(node.val)
            if len(queue) > k:
                if (abs(target - queue[0]) <= abs(target - queue[-1])):
                    queue.pop()
                    return
                else:
                    queue.popleft()
                    
            dfs(node.right, queue)
        
        queue = deque()
        dfs(root, queue)
        return list(queue)

Metadata

Metadata

Assignees

Labels

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions