These don’t need to be 3 different questions. The vocabulary (knowing what pre, in, post means) is nice, and the questions follows what I see as the “typical” recursive tree-problem skeleton.
The first one is how I think it should be solved (albeit recursively). If memory serves, doing it iteratively for infix is a bit interesting. The other two example solutions are very terse.
class Solution:
def preorderTraversal(self, root: Optional[TreeNode]) -> List[int]:
if root is None: return []
prefix = self.preorderTraversal(root.left)
suffix = self.preorderTraversal(root.right)
return [root.val] + prefix + suffix
class Solution:
def inorderTraversal(self, root: Optional[TreeNode]) -> List[int]:
if root is None:
return []
return self.inorderTraversal(root.left) + [root.val] + self.inorderTraversal(root.right)V
class Solution:
def postorderTraversal(self, root: Optional[TreeNode]) -> List[int]:
if root is None: return []
return self.postorderTraversal(root.left) + self.postorderTraversal(root.right) + [root.val]