Problem 143
Binary Tree Preorder Traversal
Easy · 10 pts · Tree, Stack, Binary Tree
Problem
You are given a binary tree. Print its preorder traversal: for every node, first visit the node itself, then its whole left subtree, then its whole right subtree. A recursive function does this directly. An iterative version uses a stack: pop a node, visit it, then push its right child and its left child, so that the left child is processed first.
Input
First line: integer N, the number of tokens. Second line: N tokens describing the tree in level order, where 'null' marks a missing child (the same format LeetCode uses).
Output
Print the values in preorder, space-separated.
Constraints
1 <= number of nodes <= 10000; -100 <= value <= 100
Example input
4 1 null 2 3
Example output
1 2 3
Explanation
The root 1 has a right child 2, and 2 has a left child 3. Preorder visits 1 first, then its (empty) left subtree, then the subtree of 2, where 2 comes before its child 3. The order is 1 2 3.