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?