In this LeetCode Q/A an answer w/o any inline comments demonstrates how to accomplish iterative in-order binary tree traversal.
class Solution:
def inorderTraversal(self, root: TreeNode) -> List[int]:
traversal = []
node = root
stack = []
while node or stack:
if node:
stack.append(node)
node = node.left
else:
node = stack.pop()
traversal.append(node.val)
node = node.right
return traversal
Why does this work? I'm primarily confused by the if node statement, which always moves to the left child. The else statement must satisfy the conditions that node does not exist but stack does exist, and this is really perplexing to me.
I'd like to understand it such that I could tweak code to perform pre or post order traversal but not understanding why this code functions, that's a bride too far.