首页 > 解决方案 > 基于变量存在的while循环中使用or和管道的写入条件差异

问题描述

我正在尝试编写一个函数来inorder遍历binary tree. 我的功能如下:

class TreeNode:
    def __init__(self, x):
        self.val = x
        self.left = None
        self.right = None

def inorderTraversal(root):
    """
    :type root: TreeNode
    :order: List[int]
    """

    stack = []
    order = []

    while stack or root:
        if root:
            stack.append(root)
            root = root.left

        else:
            current_node = stack.pop()
            order.append(current_node.val)
            root = current_node.right

    return order

现在,我对这条线感到困惑

while stack or root: # this works fine

我尝试以不同的方式编写如下:

while stack | root:

这导致函数失败并出现以下错误

TypeError: unsupported operand type(s) for |: 'list' and 'TreeNode'

大多数时候,我|用来比较if statement数据帧或数据帧中的条件indexing,它一直运行良好。

|和 和有什么不一样or?为什么在这种特殊情况下会失败?

标签: pythonpython-3.x

解决方案


|按位逻辑运算符,它可以被自定义类覆盖。or是规范逻辑运算符;它不能被覆盖,它只适用于bools。

您要询问的行利用了bool对列表类型和一般对象的隐式转换。如果stack为空,bool(stack)将返回FalseTrue否则)。同样,如果root绑定到一个None对象,那么bool(root)将返回FalseTrue否则)。

while stack or root因此等价于while len(stack) > 0 or root is not None


推荐阅读