pythonpython-3.xruntime-erroriterable-unpacking

What is the correct way to unpack a tuple composed of a TreeNode and an Integer?


I'm implementing an algorithm that requires appending and popping nodes from a Tree in python (in a FIFO way).

queue = []  # empty list
root = TreeNode()  # a standard TreeNode with val, left and right

I'm trying to store both root and an integer in the queue:

queue.append((root,0))

... and then trying to pop it:

n,l = queue.pop(0)

Now, I'm getting the following error:

TypeError: cannot unpack non-iterable TreeNode object
    ^^^
    n,l = queue.pop(0)

I tested if I could append and pop just the root node and it seems to work. The problem is the inclusion of the integer so I'm assuming my syntax is incorrect. I also tried:

queue.append(((root,0)))
queue.append(Tuple((root,0)))
queue.append([(root,0)])  # that one gave me ValueError: not enough values to unpack (expected 2, got 1)

None of them seems to work.

Can you provide any help in this matter?

Update: As requested below, here's the code portion:

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def levelOrder(self, root: Optional[TreeNode]) -> List[List[int]]:
        queue = []  # far slower than 'deque' but should work
        
        if not root:
            return queue

        queue.append((root,0))
        levels={}
        while queue:
            n,l = queue.pop(0)
            if n:
                if l not in levels:
                    levels[l] = []
                levels[l].append(n.val)
                queue.append(n.left)
                queue.append(n.right)

        return [[]]

Full error:

TypeError: cannot unpack non-iterable TreeNode object
    ^^^
    n,l = queue.pop(0)
Line 17 in levelOrder (Solution.py)
          ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    ret = Solution().levelOrder(param_1)
Line 45 in _driver (Solution.py)
    _driver()
Line 56 in <module> (Solution.py)

Solution

  • The simplified code in your question (and the syntax to unpack a tuple from the queue) basically works, so the issue is elsewhere:

    class TreeNode:
        pass
    
    
    queue = []
    root = TreeNode()
    
    queue.append((root, 0))  # A tuple.
    n, l = queue.pop(0)  # Works.
    
    queue.append(root)  # Just a node, not a tuple.
    n, l = queue.pop(0)  # Doesn't.
    

    In the full tree-traversing code, there's

    queue.append(n.left)
    queue.append(n.right)
    

    which are putting just nodes (which aren't unpackable) into your queue.

    I think you mean

    queue.append((n.left, l))
    queue.append((n.right, l))
    

    there.