Watch preorder traversal visit the root, then left, then right on a binary tree. Worked example on a five node tree, a stack version, and nodes you can edit.
About this algorithm
Pre-order traversal records a node first, then its left subtree, then its right subtree. Every parent appears before its children, so the output is a record of the tree's shape from the top down. That makes pre-order the order for copying a tree, or saving it to a file and rebuilding it later.
Use pre-order when a node must be handled before anything below it: cloning a tree, serialising it (writing it out with markers for missing children), printing a folder structure with each folder above its contents, or passing a value down from the root, such as the running total on a root-to-leaf path. Pick in-order for sorted output from a binary search tree, and post-order when a node needs results from its children. Level order also lists parents before children, but it finishes a whole level before going deeper instead of following one branch down.
At each node, write down its value straight away. The root is always the first value in the output.
Run pre-order on the left child. Everything in the left subtree is written before anything on the right.
Then run pre-order on the right child. A missing child returns immediately.
Push the root. Then repeatedly pop a node, record it, push its right child and then its left child. The left child goes on last so it comes off first, which keeps the left-before-right order.
The page's tree has root 0, left child 1 and right child 2, with 3 under 1 on the left and 4 under 2 on the right. Record 0. Go left and record 1, go left again and record 3. Nothing is left under 3 or 1, so return to 0 and go right: record 2, then its right child 4. The output is 0, 1, 3, 2, 4. The stack version gives the same list: pop 0 and push 2 then 1; pop 1 and push 3; pop 3; pop 2 and push 4; pop 4.
Pre-order alone does not say where the missing children were: 0, 1, 3, 2, 4 fits more than one tree shape. Either write a marker such as # for every missing child, giving 0, 1, 3, #, #, #, 2, #, 4, #, # for this tree, or pair the pre-order with the in-order list. The first pre-order value is the root, and its position in the in-order list splits the left subtree from the right.
Time: each node is recorded once and each child link is followed once, so the work grows with N. Space: the recursion holds the current path from the root, up to the height H; the stack version holds about one waiting right child per level, also O(H).