python中双端队列中元素的比较

发布于 2025-01-17 05:08:00 字数 298 浏览 3 评论 0原文

有人可以解释一下,如何比较双端队列中的树节点。例如,我将两个相同二叉树的两个子节点推送到两个不同的双端队列中,得到 deque1 = deque([TreeNode{val: 2, left: None, right: None}, TreeNode{val: 3, left:无,右:无}]),deque2 = deque([TreeNode{val: 2,左:无,右:无},TreeNode{val: 3,左:无,右:无}]),但是当我比较它们时,我得到False。为什么如果两个双端队列包含相同的节点,它们不相等?先感谢您!

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!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

拥抱没勇气 2025-01-24 05:08:00

您的想法是正确的,如果您的 deque 对象包含相同的对象,那么两个 deque 实例也将被评估为相等。您遇到的问题是,复杂对象(例如 TreeNode 的实例)默认情况下仅当它们是同一对象时才相等,而不一定是它们具有相同的内容。这是一个简化的示例:

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

看看这篇文章 有关如何解决该问题的一些提示。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文