defpreorder(root:TreeNode)->List[int]:res,stack=[],[(root,False)]whilestack:node,visited=stack.pop()# the last elementifnode:ifvisited:res.append(node.val)else:# preorder: root -> left -> rightstack.append((node.right,False))stack.append((node.left,False))stack.append((node,True))returnres
definorder(root:TreeNode)->List[int]:res,stack=[],[(root,False)]whilestack:node,visited=stack.pop()# the last elementifnode:ifvisited:res.append(node.val)else:# inorder: left -> root -> rightstack.append((node.right,False))stack.append((node,True))stack.append((node.left,False))returnres
defpostorder(root:TreeNode)->List[int]:res,stack=[],[(root,False)]whilestack:node,visited=stack.pop()# the last elementifnode:ifvisited:res.append(node.val)else:# postorder: left -> right -> rootstack.append((node,True))stack.append((node.right,False))stack.append((node.left,False))returnres