Issue
I am learning to use a deque to check if two binary trees are the same. However, I can't figure out why n1 and n2 (as node1 and node2) can't be unpacked. I tried to put them in a list and a tuple, unpacking, etc, but can't unpack successfully. I'm thinking it's something else. Could anyone help? Here is the code:
def iterative(self, p, q):
q = deque( [p, q] )
while len(q) > 0:
n1, n2 = q.popleft()
if not n1 and not n2: pass
elif not n1 or not n2: return False
else:
if n1.val != n2.val: return False
q.append( [n1.left, n2.left] )
q.append( [n1.right, n2.right] )
return True
Solution
The problem is in how you initialise the deque. The constructor expects an iterable of entries, and as you intend an entry to be a pair, you need to provide an iterable of pairs. But instead you provided just a pair, which it is interpreted as a sequence of two entries, each being a singe node and not a pair. This means your deque starts out with two entries instead of one, and each entry is a node, not a pair of nodes.
Change this:
q = deque( [p, q] )
to this:
q = deque( [[p, q]] )
Answered By - trincot
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.