defiterative_inorder(self, root: TreeNode) -> List[int]: ifnot root: return [] res, stack = [], [] it = root while it: stack.append(it) it = it.left while stack: node = stack.pop() res.append(node.val) if node.right: n = node.right while n: stack.append(n) n = n.left return res
defiterative_preorder(self, root: TreeNode) -> List[int]: ifnot root: return [] res, stack = [], [] it = root while it: stack.append(it) res.append(it.val) it = it.left while stack: node = stack.pop() if node.right: n = node.right while n: stack.append(n) res.append(n.val) n = n.left return res
defiterative_postorder(self, root: TreeNode) -> List[int]: ifnot root: return [] res, stack = [], [] it = root while it: stack.append((it, 0)) # count for it in the stack top it = it.left while stack: pair = stack.pop() node = pair[0] occurrence = pair[1] + 1 if occurrence == 2: res.append(node.val) continue# don't iterate on right node again else: stack.append((node, occurrence)) if node.right: n = node.right while n: stack.append((n, 0)) n = n.left return res