Problem Description
Given the root of a binary tree, return the preorder traversal of its nodes' values. In preorder traversal, you visit the root node first, then recursively do a preorder traversal of the left subtree, followed by a recursive preorder traversal of the right subtree.
Key Insights
- Preorder traversal follows the order: Root -> Left -> Right.
- A recursive solution is straightforward but the problem asks for an iterative solution.
- Use a stack to simulate the recursive function call behavior.
- When using a stack, push the right child first so that left is processed before right.
Space and Time Complexity
Time Complexity: O(N), where N is the number of nodes, because every node is visited once. Space Complexity: O(N) in the worst case due to the stack when the tree is unbalanced.
Solution
We use an iterative approach with a stack. Start by pushing the root to the stack. While the stack is not empty, pop the top node from the stack, record its value, and push its right child (if exists) followed by its left child (if exists) to the stack. This ensures that the left child is processed before the right child, adhering to the preorder traversal order.