Binary Tree Preorder Traversal
Given the root of a binary tree, return the preorder traversal of its node values: the node first, then its left subtree, then its right subtree.
Open on LeetCode ↗Intuition
Preorder visits a node the moment it's discovered — record first, explore later. It's the order you'd photocopy a tree: root, then everything under the left child, then everything under the right.
Approach
Visit before you descend
The only difference from inorder is where the append sits: record node.val before the two recursive calls. That single line move changes the output order completely — a good reminder that all three DFS traversals are the same walk, differing only in when they look at the node.
Why preorder matters
Because the root comes first, preorder is the natural order for copying or serializing a tree — you can rebuild the tree by reading the list left to right. It's also plain DFS order, the same sequence a stack-based explorer would discover nodes in.
Iterative version is the easiest of the three
Push root; loop: pop, visit, push right then left (right first so left pops first). No revisiting logic needed since the node is handled the moment it's popped.
Solution & live demo
Edge cases
Base case returns immediately — empty list.
Each node is visited then recursion slides right; output equals the top-to-bottom chain.
Visited immediately; both child calls hit the base case.