Can someone explain me, how works comparing of tree nodes in deque. For example, I pushed two children of two same binary trees in two different deques and I got deque1 = deque([TreeNode{val: 2, left: None, right: None}, TreeNode{val: 3, left: None, right: None}])
, deque2 = deque([TreeNode{val: 2, left: None, right: None}, TreeNode{val: 3, left: None, right: None}])
, but when I compared them, I got False
. Why if two deques includes same nodes they are not equal? Thank you in advance!
CodePudding user response:
You are right in thinking that if your deque
objects contained equal objects then the two deque
instances would also evaluate to be equal. The problem you are running into is that complex objects, like instances of TreeNode
, by default are equal only if they are the same object, not necessarily if they have have the same contents. Here is a simplified example:
class TreeNode():
def __init__(self,val, left, right):
self.val = val
self.left = left
self.right = right
t1 = TreeNode(2, None, None)
t2 = TreeNode(2, None, None)
print(t1 == t2)
print(t1 == t1)
False
True
Take a look at this post for some tips on how to work around the issue.