-1

I am trying to write a function to do inorder traversal for a binary tree. My function is as follows:

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

Now, I am confused with this line

while stack or root: # this works fine

I tried to write it differently as follows:

while stack | root:

this caused the function to fail with the following error

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

Most of the times, I use | to compare conditions in if statement or dataframe indexing and it has been working fine.

What is the difference between | and or? Why does it fail in this particular case?

billydh
  • 763
  • 4
  • 19

2 Answers2

1

| is a bitwise logical operator, and it can be overridden by custom classes. or is the canonical logical operator; it can't be overridden, it only works on bools.

The line you're asking about takes advantage of implicit conversion to bool type of lists—and objects in general. If stack is empty, bool(stack) will return False (and Trueotherwise). Similarly, if root is bound to a None object, then bool(root) will return False (and Trueotherwise).

while stack or root is thus equivalent to while len(stack) > 0 or root is not None.

Anakhand
  • 1,754
  • 11
  • 30
0

or is a logical or, that you use in if-tests: it returns True if either of its operands is true-ish.

| is a bitwise or: it is used for manipulating bit-strings: for example 0b101 | 0b010 == 0b111.

BoarGules
  • 13,647
  • 2
  • 23
  • 38