TreeNode(val, left=None, right=None) is in the starter. Keep it.
Every tree recursion is one of three orders, depending on when you handle the node relative to its subtrees. Write all three, each returning the list of values visited:
preorder(root): node, then left subtree, then right subtree.inorder(root): left, node, right. (For a binary search tree this is sorted order.)postorder(root): left, right, node.
An empty tree (None) gives [].
# 1
# / \
# 2 3
# / \
# 4 5
preorder(root) # [1, 2, 4, 5, 3]
inorder(root) # [4, 2, 5, 1, 3]
postorder(root) # [4, 5, 2, 3, 1]
Up to 500 nodes, so plain recursion is fine. Values may repeat or be negative.
Show hint
all three share one recursive skeleton; only the line that records node.val moves.