Opening the reading…
Opening the reading…
BINARY TREE › TRAVERSALS
Open — the attempt gate is not wired up yet
This editorial is meant to unlock after you have run the problem at least once, with the worked solution behind one further deliberate click. That needs per-learner unlock state nothing stores today, so for now the whole article is open.
Try it yourself first →Inorder traversal has one exact order: finish the left subtree, visit the node, then finish the right subtree. When recursion visits a node, it quietly remembers that node while it travels left, then returns to it after the left side is done. The iterative solution must make that hidden memory explicit.
Start at the root and push every node on the path to the leftmost node. The top of the stack is then the next node whose left subtree is complete, so pop it, record its value, and continue from its right child. If that right child exists, its entire left path becomes the next work to push. The stack therefore contains exactly the ancestors that are waiting for their turn.
| MEASURE | BOUND | WHY |
|---|---|---|
| Time | O(n) | Each node is pushed once, popped once, and appended once. Moving left or right only advances through an edge or processes a node, so no node or edge is revisited by a second traversal. |
| Space | O(h) extra space | The result vector is required output and is excluded. The stack contains only the current root-to-leaf path and waiting ancestors, so it uses O(h); this is O(log n) for a balanced tree and degrades to O(n) for a completely one-sided tree. |
#include <stack>
#include <vector>
using namespace std;
class Solution {
public:
vector<int> inorderTraversal(TreeNode* root) {
vector<int> res;
stack<TreeNode*> stk;
TreeNode* curr = root;
while (curr != nullptr || !stk.empty()) {
while (curr != nullptr) {
stk.push(curr);
curr = curr->left;
}
curr = stk.top();
stk.pop();
res.push_back(curr->val);
curr = curr->right;
}
return res;
}
};The outer loop uses an OR, not an AND. After the left descent reaches null, curr is empty but the stack still contains ancestors to process. After popping a node, assigning curr to its right child either starts another descent or leaves the stack to supply the next ancestor. Those two assignments are what connect separate left paths into one continuous traversal.