Problem Description
Given the root of a binary tree, return the inorder traversal of its nodes' values. In an inorder traversal, you visit the left subtree first, then the current node, and finally the right subtree. Although a recursive solution is straightforward, the challenge is to implement this traversal iteratively.
Key Insights
- Inorder traversal pattern: left subtree → node → right subtree.
- An iterative solution uses a stack to simulate the recursive process.
- Continuously move to the leftmost node and store nodes in the stack.
- After reaching a null, backtrack by popping from the stack, process the node, and then explore its right subtree.
- Handle edge cases such as an empty tree.
Space and Time Complexity
Time Complexity: O(n) - Every node is visited once. Space Complexity: O(n) - In the worst-case scenario (skewed tree), the stack may store all nodes.
Solution
The problem can be solved using an iterative approach that simulates the behavior of recursion with a stack. Start with the root node, then push each left child onto the stack until reaching a null node. Once you hit null, pop the last node from the stack, process it, and then move to its right child. Repeat this process until there are no nodes left to process. This method ensures that nodes are processed in their correct inorder sequence.