{"id":"binary-tree-inorder-traversal","title":"Binary Tree Inorder Traversal","difficulty":"easy","patterns":["tree-dfs"],"primaryConcept":"tree-dfs-basics","concepts":["tree-dfs-basics"],"problemForm":"intro","companies":[],"category":"trees-graphs","compareMode":"exact","description":"Given the root of a binary tree, return the inorder traversal of its node values.\n\nInorder traversal visits the left subtree first, then the current node, then the right subtree.","examples":[{"input":"root = {\"val\":1,\"left\":null,\"right\":{\"val\":2,\"left\":{\"val\":3},\"right\":null}}","output":"[1,3,2]","explanation":"Visit 1, then the left child of 2, then 2."},{"input":"root = null","output":"[]","explanation":"An empty tree has no values."},{"input":"root = {\"val\":1}","output":"[1]","explanation":"A single-node tree returns that one value."}],"constraints":[{"id":"the-number-of-nodes-in-the-tree-is-in-the-range-0-100","text":"The number of nodes in the tree is in the range [0, 100]","check":{"kind":"sizeRange","target":"root","measure":"treeNodes","min":0,"max":100}},{"id":"100-node-val-100","text":"-100 <= Node.val <= 100","check":{"kind":"valueRange","target":"root","selector":"treeValues","min":-100,"max":100}}],"starterCode":"# TraceCode provides TreeNode at runtime.\n# class TreeNode:\n#     def __init__(self, val=0, left=None, right=None):\n#         self.val = val\n#         self.left = left\n#         self.right = right\n\nclass Solution:\n    def inorderTraversal(self, root: TreeNode | None) -> list[int]:\n        # Your code here\n        pass","functionName":"inorderTraversal","testCases":[{"id":"1","input":{"root":{"__type__":"TreeNode","__id__":"tree-0","val":1,"left":null,"right":{"__type__":"TreeNode","__id__":"tree-1","val":2,"left":{"__type__":"TreeNode","__id__":"tree-2","val":3,"left":null,"right":null},"right":null}}},"expected":[1,3,2],"description":"Right child with a left subtree."},{"id":"2","input":{"root":null},"expected":[],"description":"Empty tree."},{"id":"3","input":{"root":{"__type__":"TreeNode","__id__":"tree-0","val":1,"left":null,"right":null}},"expected":[1],"description":"Single node."},{"id":"4","input":{"root":{"__type__":"TreeNode","__id__":"tree-0","val":1,"left":{"__type__":"TreeNode","__id__":"tree-1","val":2,"left":{"__type__":"TreeNode","__id__":"tree-3","val":4,"left":null,"right":null},"right":{"__type__":"TreeNode","__id__":"tree-4","val":5,"left":{"__type__":"TreeNode","__id__":"tree-6","val":6,"left":null,"right":null},"right":{"__type__":"TreeNode","__id__":"tree-7","val":7,"left":null,"right":null}}},"right":{"__type__":"TreeNode","__id__":"tree-2","val":3,"left":null,"right":{"__type__":"TreeNode","__id__":"tree-5","val":8,"left":{"__type__":"TreeNode","__id__":"tree-8","val":9,"left":null,"right":null},"right":null}}}},"expected":[4,2,6,5,7,1,3,9,8],"description":"Imported trusted-corpus tree."},{"id":"h1","input":{"root":{"__type__":"TreeNode","__id__":"tree-h1-0","val":2,"left":{"__type__":"TreeNode","__id__":"tree-h1-1","val":1,"left":null,"right":null},"right":{"__type__":"TreeNode","__id__":"tree-h1-2","val":3,"left":null,"right":null}}},"expected":[1,2,3],"description":"A balanced three-node tree."},{"id":"h2","input":{"root":{"__type__":"TreeNode","__id__":"tree-h2-0","val":1,"left":null,"right":{"__type__":"TreeNode","__id__":"tree-h2-1","val":2,"left":null,"right":{"__type__":"TreeNode","__id__":"tree-h2-2","val":3,"left":null,"right":null}}}},"expected":[1,2,3],"description":"A right-skewed tree preserves order by left-first traversal."},{"id":"h3","input":{"root":{"__type__":"TreeNode","__id__":"tree-h3-0","val":1,"left":{"__type__":"TreeNode","__id__":"tree-h3-1","val":2,"left":{"__type__":"TreeNode","__id__":"tree-h3-2","val":3,"left":null,"right":null},"right":null},"right":null}},"expected":[3,2,1],"description":"A left-skewed tree reverses the node order."},{"id":"h4","input":{"root":{"__type__":"TreeNode","__id__":"tree-h4-0","val":4,"left":{"__type__":"TreeNode","__id__":"tree-h4-1","val":2,"left":{"__type__":"TreeNode","__id__":"tree-h4-2","val":1,"left":null,"right":null},"right":{"__type__":"TreeNode","__id__":"tree-h4-3","val":3,"left":null,"right":null}},"right":{"__type__":"TreeNode","__id__":"tree-h4-4","val":6,"left":{"__type__":"TreeNode","__id__":"tree-h4-5","val":5,"left":null,"right":null},"right":{"__type__":"TreeNode","__id__":"tree-h4-6","val":7,"left":null,"right":null}}}},"expected":[1,2,3,4,5,6,7],"description":"A full tree produces a sorted inorder sequence here."},{"id":"h5","input":{"root":{"__type__":"TreeNode","__id__":"tree-h5-0","val":1,"left":null,"right":{"__type__":"TreeNode","__id__":"tree-h5-1","val":2,"left":{"__type__":"TreeNode","__id__":"tree-h5-2","val":3,"left":null,"right":null},"right":null}}},"expected":[1,3,2],"description":"A left child hanging off the right subtree is visited in between."},{"id":"h6","input":{"root":{"__type__":"TreeNode","__id__":"tree-h6-0","val":2,"left":{"__type__":"TreeNode","__id__":"tree-h6-1","val":1,"left":null,"right":null},"right":{"__type__":"TreeNode","__id__":"tree-h6-2","val":4,"left":{"__type__":"TreeNode","__id__":"tree-h6-3","val":3,"left":null,"right":null},"right":null}}},"expected":[1,2,3,4],"description":"The right subtree contributes an interior left branch."},{"id":"zero-and-negative-values","input":{"root":{"__type__":"TreeNode","val":0,"left":{"__type__":"TreeNode","val":-3,"left":null,"right":null},"right":{"__type__":"TreeNode","val":2,"left":{"__type__":"TreeNode","val":-1,"left":null,"right":null},"right":null}}},"expected":[-3,0,-1,2],"description":"Inorder traversal preserves zero and negative node values in left-root-right order."}],"hints":[{"level":1,"content":"Inorder traversal delays visiting a node until after its left subtree.","revealPattern":false},{"level":2,"content":"Use a stack to remember nodes while walking down the left spine.","revealPattern":true},{"level":3,"content":"After popping and recording a node, continue with its right subtree.","revealPattern":true}],"guidedFlow":{"progressRevision":"binary-tree-inorder-traversal-2026-07-19-derived-loop-guard","approachSelection":{"contract":"approach-selection-v1","question":"How should the deferred nodes be remembered?","decisionPrompt":"Choose the approach whose state and complexity match the problem constraints.","approaches":[{"id":"recursive-dfs","name":"Recursive DFS","summary":"Recurse left, record the node, recurse right, letting the call stack remember ancestors.","decisionReason":"Recursive DFS emits the same left, node, right order. The guided implementation exposes the deferred ancestors in a stack so every pause and right turn can be traced directly.","complexity":{"time":"O(n)","space":"O(h)"},"tradeoffs":["Runs in O(n) time and uses O(h) call-stack space."],"isViable":true,"isOptimal":false},{"id":"iterative-stack","name":"Explicit stack traversal","summary":"Walk the left spine pushing each node, then pop to record and turn right.","decisionReason":"Holds the deferred nodes in a real stack you can see and bound, reaching the same left-node-right order in O(n) time and O(h) space.","complexity":{"time":"O(n)","space":"O(h)"},"tradeoffs":["Runs in O(n) time and uses O(h) stack space."],"isOptimal":true}]},"codingCheckpoints":[{"id":"init-stack","title":"Set up the result, the stack, and current","description":"Start an empty result list, an empty stack for deferred nodes, and current at the root.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"tree","fact":"initializes_stack_traversal_state","scope":"init-stack","readMode":"tree-value-query-v1"}]},"commonMistakes":["Skipping the stack and trying to track ancestors with a single pointer","Starting current somewhere other than the root"],"hint":"You need a place to collect values, a stack for the nodes you pass on the way down, and current for the active descent.","semanticSpec":{"intent":"Set up the explicit stack traversal state.","doneWhen":"This step is done when an empty stack and current at the root both exist alongside the result.","shouldFailWhen":"This step should fail if there is no stack to hold deferred nodes.","roles":["algorithm state","result state"],"mustProve":["This step is done when an empty stack and current at the root both exist alongside the result."],"mustNotAccept":["This step should fail if there is no stack to hold deferred nodes."],"proofSnippets":[{"id":"py-inorder-init-stack","language":"python","code":"class Solution:\n    def inorderTraversal(self, root):\n        result = []\n        stack = []\n        current = root"}]}},{"id":"left-spine","title":"Push each node while walking down the left","description":"While current exists, push it and move to its left child, descending until the left side runs out.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"tree","fact":"pushes_cursor_and_descends_child_link","scope":"left-spine","readMode":"tree-value-query-v1"}]},"commonMistakes":["Recording a node before its left subtree is finished","Moving right while a left child still remains"],"hint":"Pushing a node defers it until everything to its left has been recorded.","semanticSpec":{"intent":"Defer each node by pushing it before descending to its left child.","doneWhen":"This step is done when current is pushed and then advanced to its left child link.","shouldFailWhen":"This step should fail if the node is not pushed before the descent.","roles":["algorithm state","result state"],"mustProve":["This step is done when current is pushed and then advanced to its left child link."],"mustNotAccept":["This step should fail if the node is not pushed before the descent."],"proofSnippets":[{"id":"py-inorder-left-spine","language":"python","code":"class Solution:\n    def inorderTraversal(self, root):\n        result = []\n        stack = []\n        current = root\n        while current:\n            stack.append(current)\n            current = current.left"}]}},{"id":"visit-node","title":"Pop the top node and record its value","description":"When the left side runs out, pop the most recent node and append its value to the result.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"tree","fact":"records_popped_node_value","scope":"visit-node","readMode":"tree-value-query-v1"}]},"commonMistakes":["Recording a value before popping it from the stack","Appending the node itself instead of its value"],"hint":"The newest deferred node is the next one whose left subtree is finished, so the top of the stack is next in order.","semanticSpec":{"intent":"Record the deferred node once its left subtree is done.","doneWhen":"This step is done when a popped stack entry drives the value appended to the result.","shouldFailWhen":"This step should fail if the appended value is not tied to the popped node.","roles":["algorithm state","result state"],"mustProve":["This step is done when a popped stack entry drives the value appended to the result."],"mustNotAccept":["This step should fail if the appended value is not tied to the popped node."],"proofSnippets":[{"id":"py-inorder-visit-node","language":"python","code":"class Solution:\n    def inorderTraversal(self, root):\n        result = []\n        stack = []\n        current = root\n        while current or stack:\n            while current:\n                stack.append(current)\n                current = current.left\n            current = stack.pop()\n            result.append(current.val)"}]}},{"id":"right-subtree","title":"Turn current to the right child","description":"After recording a node, move current to its right child so the right subtree is traversed next.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"tree","fact":"advances_to_deferred_child_link","scope":"right-subtree","readMode":"tree-value-query-v1"}]},"commonMistakes":["Returning to the left child a second time","Dropping the right subtree entirely"],"hint":"Left and the node itself are both done, so only the right subtree remains for that node.","semanticSpec":{"intent":"Continue from the recorded node into its right subtree.","doneWhen":"This step is done when popped current advances to its right child link after the value is recorded.","shouldFailWhen":"This step should fail if current never advances after the pop.","roles":["algorithm state","result state"],"mustProve":["This step is done when popped current advances to its right child link after the value is recorded."],"mustNotAccept":["This step should fail if current never advances after the pop."],"proofSnippets":[{"id":"py-inorder-right-subtree","language":"python","code":"class Solution:\n    def inorderTraversal(self, root):\n        result = []\n        stack = []\n        current = root\n        while current or stack:\n            while current:\n                stack.append(current)\n                current = current.left\n            current = stack.pop()\n            result.append(current.val)\n            current = current.right"}]}},{"id":"return-traversal","title":"Return the recorded values","description":"Once current is empty and the stack is empty, return the collected result list.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"tree","fact":"returns_stack_traversal_result","scope":"return-traversal","readMode":"tree-value-query-v1"}]},"commonMistakes":["Returning the stack instead of the result list","Returning from inside the loop before the traversal finishes"],"hint":"The traversal is done only when there is no current node and nothing deferred on the stack.","semanticSpec":{"intent":"Return the collected inorder sequence.","doneWhen":"This step is done when the traversal returns the accumulated result list.","shouldFailWhen":"This step should fail if the collected result is never returned.","roles":["algorithm state","result state"],"mustProve":["This step is done when the traversal returns the accumulated result list."],"mustNotAccept":["This step should fail if the collected result is never returned."],"proofSnippets":[{"id":"py-inorder-return-traversal","language":"python","code":"class Solution:\n    def inorderTraversal(self, root):\n        result = []\n        stack = []\n        current = root\n        while current or stack:\n            while current:\n                stack.append(current)\n                current = current.left\n            current = stack.pop()\n            result.append(current.val)\n            current = current.right\n        return result"}]}}],"version":2,"slides":[{"id":"the-task","chapter":"The order","kind":"info","eyebrow":"Read the problem","title":"Left, then the node, then right","workspacePanel":"problem","body":["An inorder traversal reads a binary tree in one fixed order: finish a node's entire left subtree, record the node, then do its right subtree. The same rule applies at every node, all the way down.","No value moves. The only question is the order in which the nodes are read out."]},{"id":"pattern-quiz","chapter":"The order","kind":"choice","source":"pattern-recognition","eyebrow":"Read the signal","title":"Which clue decides how to walk the tree?","workspacePanel":"problem","quiz":{"contract":"pattern-recognition-v1","question":"Which clue decides how to walk the tree?","signalPrompt":"One requirement in the order fixes when a node can be recorded.","options":[{"id":"left-before-node","label":"A node cannot be recorded until its left subtree is finished","signal":"The order forces work to be held back, which is the whole difficulty here.","rationale":"Recording is delayed until the left side is done, so a node reached early may be recorded much later. That delay is what the algorithm has to manage.","isCorrect":true},{"id":"by-depth","label":"Nodes are read shallowest-first, level by level","signal":"This is a real traversal order, but it is not left-node-right.","rationale":"Reading by depth is level order; it ignores the left-then-node-then-right rule the problem states.","isCorrect":false},{"id":"by-value","label":"Nodes are read in sorted value order","signal":"This notices values, but the tree is not promised to be sorted.","rationale":"Inorder equals sorted order only for a binary search tree; a general binary tree has no such guarantee.","isCorrect":false},{"id":"encounter-order","label":"Nodes are read in the order you first reach them from the root","signal":"This sounds simplest, but it skips the delay the order requires.","rationale":"Reaching a node is not recording it: a node with a left subtree is reached early but recorded late.","isCorrect":false}],"missFeedback":"The deciding rule is the delay: a node waits until its entire left subtree has been recorded."}},{"id":"defer-probe","chapter":"The idea","kind":"case-probe","eyebrow":"Preserve the unfinished work","title":"The cursor leaves node 2 for its left child 3. What must survive that move?","workspacePanel":"visualizer","summary":"The order rule already says 2 must wait. Once the cursor moves to 3, it no longer points at 2.","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"at-two","state":{"tree":[1,null,2,null,null,3],"node":2,"swapped":[5]}}]},"options":[{"id":"remember-two","label":"Remember node 2 so it can be recorded after 3, then continue to 2's right side","rationale":"Moving the cursor left loses the direct reference to 2. Saving the node preserves both unfinished jobs: record 2 when its left subtree ends, then enter its right subtree.","isCorrect":true},{"id":"remember-three","label":"Remember only node 3 because it is the next value to record","rationale":"The cursor already moves to 3, so 3 is not the reference at risk. Node 2 is the unfinished work that would be lost when the cursor leaves it.","isCorrect":false},{"id":"save-nothing","label":"Save nothing; after 3, the traversal can rediscover node 2 from the root","rationale":"Restarting from the root would repeat work and still require tracking which nodes were unfinished. Preserving node 2 directly keeps the traversal moving forward.","isCorrect":false}],"answer":"Remember node 2 while the cursor goes left. When 3's subtree finishes, that saved reference tells the traversal which node to record and which right subtree comes next."},{"id":"structure-probe","chapter":"The idea","kind":"case-probe","eyebrow":"Name the state","title":"When several set-aside nodes are waiting, which one gets recorded first?","workspacePanel":"visualizer","summary":"Walking 2 then 3 down the left, both are set aside before either is recorded.","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"two-waiting","state":{"tree":[1,null,2,null,null,3],"node":5,"swapped":[2]}}]},"options":[{"id":"newest","label":"The most recently set-aside node, because its left subtree finishes first","rationale":"You descended to 3 last, so its left side empties first; the waiting nodes come back newest-first, which is exactly a stack.","isCorrect":true},{"id":"oldest","label":"The first node set aside, since it has waited longest","rationale":"The earliest node set aside (the shallowest) still has a whole left subtree below it, so it is recorded after the deeper nodes.","isCorrect":false},{"id":"smallest","label":"Whichever has the smallest value","rationale":"Order comes from links and descent, not from comparing values; the tree is not assumed sorted.","isCorrect":false}],"answer":"Newest-first: the last node you set aside is the first ready to record. That last-in-first-out order is a stack."},{"id":"after-pop-probe","chapter":"The idea","kind":"case-probe","eyebrow":"Finish the node","title":"Node 3 was just recorded. Where does the cursor go next?","workspacePanel":"visualizer","summary":"The stack held 2 below 3. Now 3 has been popped and recorded, while node 2 is still waiting.","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"three-done","state":{"tree":[1,null,2,null,null,3],"node":5,"stack":[2],"visited":[0,5]}}]},"options":[{"id":"right-child","label":"Into node 3's right subtree, even though it is empty","rationale":"After recording a node, the uniform update is to turn right. Here that makes the cursor null, while the stack still preserves node 2.","isCorrect":true},{"id":"back-up","label":"Pop node 2 immediately without checking 3's right child","rationale":"Node 3 happens to have no right child, but the traversal rule is still left, node, then right. The cursor must take that right link before the outer loop decides what work remains.","isCorrect":false},{"id":"stop","label":"Stop, since node 3 has no children","rationale":"Node 3 is finished, but node 2 remains deferred on the stack. Finishing one branch does not finish the traversal.","isCorrect":false}],"answer":"Turn the cursor to node 3's right child. It becomes null here, but node 2 is still on the stack; the traversal must preserve both sources of unfinished work."},{"id":"dry-run-setup","chapter":"Trace","kind":"info","eyebrow":"Watch it move","title":"Push down the left, pop to record, turn right","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"setup","state":{"tree":[1,null,2,null,null,3],"node":0}}]},"body":["The cursor starts at the root and the stack is empty. Each round pushes nodes down the left until there is no left child, then pops the top node, records it, and turns the cursor to that node's right child.","Watch the order the values come out on this tree: pushing happens 1, then 2, then 3, but recording does not."]},{"id":"trace","chapter":"Trace","kind":"dry-run","source":"trace-example","eyebrow":"Trace the order","title":"Trace the stack order","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"visit-one","state":{"tree":[1,null,2,null,null,3],"node":0,"stack":[],"visited":[]}},{"id":"descend-three","state":{"tree":[1,null,2,null,null,3],"node":5,"swapped":[2],"stack":[2,3],"visited":[0]}},{"id":"pop-order","state":{"tree":[1,null,2,null,null,3],"node":2,"stack":[2],"visited":[0,5]}}]},"beats":[{"id":"visit-one","title":"Node 1 has no left child. What happens to it?","summary":"The cursor sits on node 1, with the stack and result still empty.","prompt":"The cursor is at node 1.","options":[{"id":"push-pop-one","label":"It is pushed, then immediately popped and recorded","rationale":"Every node is pushed on the descent; with no left child, 1's left side is already done, so it pops and is recorded at once.","isCorrect":true},{"id":"skip-push","label":"It is recorded directly without touching the stack","rationale":"The code pushes uniformly, then pops; 1 still rides the stack, it just does not wait there.","isCorrect":false},{"id":"wait","label":"It waits on the stack until the end","rationale":"A node waits only while its left subtree is unfinished; 1 has no left subtree, so it leaves immediately.","isCorrect":false}],"answer":"Pushed then popped at once: with no left child, node 1 is recorded first, and the cursor turns to its right child 2."},{"id":"descend-three","title":"At node 2 the walk descends left to 3. Which value is recorded next?","summary":"The descent bottomed out with 2 then 3 on the stack and only 1 recorded.","prompt":"The descent has just bottomed out.","options":[{"id":"three","label":"3, the node on top of the stack","rationale":"Node 3 was set aside last and has no left child, so it is popped and recorded before 2.","isCorrect":true},{"id":"two","label":"2, since the walk reached it first","rationale":"2 was reached first but it is owed its left subtree; 3 must be recorded before 2.","isCorrect":false},{"id":"one","label":"1 again, to close its subtree","rationale":"1 is already recorded and off the stack; the walk never records a node twice.","isCorrect":false}],"answer":"3 is recorded next. It is on top of the stack with no left subtree, so it comes out before 2."},{"id":"pop-order","title":"After 3 is recorded, what is the final result?","summary":"The result holds [1, 3] and node 2 is still on the stack.","prompt":"The last deferred node is ready to pop.","options":[{"id":"one-three-two","label":"[1, 3, 2]","rationale":"With 3 done, 2's left subtree is finished, so 2 is popped and recorded last, giving [1, 3, 2].","isCorrect":true},{"id":"one-two-three","label":"[1, 2, 3]","rationale":"That is the order the nodes were reached. Recording comes later: 3 is recorded before 2.","isCorrect":false},{"id":"three-two-one","label":"[3, 2, 1]","rationale":"Node 1 was recorded first, not last; the result starts with 1.","isCorrect":false}],"answer":"[1, 3, 2]. Node 2 was held until its left child 3 was recorded, so it lands last."}]},{"id":"outer-loop-guard-probe","chapter":"Trace","kind":"case-probe","eyebrow":"Define unfinished work","title":"The cursor is empty, but node 2 is still on the stack. Is the traversal finished?","summary":"Node 3 was just recorded and has no right child, so current is null. Node 2 was deferred earlier and still has not been recorded.","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"cursor-empty-stack-live","state":{"tree":[1,null,2,null,null,3],"node":2,"stack":[2],"visited":[0,5],"values":{"current":null,"stackHasWork":true}}}]},"options":[{"id":"cursor-or-stack","label":"No; continue while the cursor exists or the stack still holds a node","rationale":"An empty cursor only means the latest branch ended. The stack proves node 2 is still owed a visit, so the outer loop must continue when either source of work remains.","isCorrect":true},{"id":"cursor-only","label":"Yes; a null cursor means there is nowhere else to go","rationale":"The cursor has reached the end of node 3's branch, but node 2 is still deferred on the stack. Stopping now would return [1, 3] and lose node 2.","isCorrect":false},{"id":"stack-only","label":"No; from now on, continue only while the stack is nonempty","rationale":"The stack matters at this moment, but after a pop the cursor may enter a right subtree even when the stack is empty. The loop must recognize work from either place.","isCorrect":false}],"answer":"The traversal is not finished. Continue while current exists or the stack is nonempty: the cursor represents a subtree ready to descend, and the stack represents nodes still waiting to be recorded."},{"id":"record-on-reach-pitfall","chapter":"Trace","kind":"pitfall","eyebrow":"Diagnose the shortcut","title":"A cursor-only loop strands nodes that are still waiting","workspacePanel":"trace","summary":"This tempting version stops as soon as the cursor is empty. Trace the exact moment node 2 remains on the stack after node 3 has no right child.","pitfall":"The outer loop guard reads `while current` instead of `while current or stack`.","whyItMatters":"When the cursor turns right into an empty subtree, `current` becomes null while node 2 is still waiting on the stack, so the loop stops early and returns [1, 3]. The fix is to loop while `current or stack`, so a deferred node still on the stack pulls the loop back around to be popped.","negativeTrace":{"contract":"negative-trace-v1","languageLabel":"Python","editorLanguage":"python","code":"def inorderTraversal(root: TreeNode | None) -> list[int]:\n    result = []\n    stack = list()\n    current = root\n    while current:\n        while current:\n            stack.append(current)\n            current = current.left\n        current = stack.pop()\n        result.append(current.val)\n        current = current.right\n    return result","steps":[{"id":"record-one","title":"Node 1 is pushed, popped, and recorded","codeLine":10,"summary":"current starts at 1, which has no left child, so 1 is pushed, popped, recorded, and the cursor turns right to 2.","state":{"tree":[1,null,2,null,null,3],"node":2,"stack":[],"visited":[0]}},{"id":"push-two-three","title":"Node 2 and node 3 are pushed down the left","codeLine":7,"summary":"From 2 the inner loop pushes 2, then 3, then the cursor falls off the bottom to null.","state":{"tree":[1,null,2,null,null,3],"node":5,"swapped":[2],"stack":[2,3],"visited":[0]}},{"id":"record-three","title":"Node 3 is popped and recorded","codeLine":10,"summary":"3 pops, is recorded, and its empty right child sets the cursor to null, leaving 2 alone on the stack.","state":{"tree":[1,null,2,null,null,3],"node":5,"stack":[2],"visited":[0,5]}},{"id":"loop-stops-early","title":"The cursor is null, so the outer loop quits","codeLine":5,"summary":"current is null, so `while current` is false and the loop ends, returning [1, 3] with node 2 still stranded on the stack.","state":{"tree":[1,null,2,null,null,3],"node":2,"swapped":[2],"stack":[2],"visited":[0,5]}}],"localizations":{"javascript":{"languageLabel":"JavaScript","editorLanguage":"javascript","codeStyle":"natural","code":"const result = [];\nconst stack = [];\nlet current = root;\nwhile (current != null) {\n    while (current != null) {\n        stack.push(current);\n        current = current.left;\n    }\n    current = stack.pop();\n    result.push(current.val);\n    current = current.right;\n}\nreturn result;","lineMap":{"2":1,"3":2,"4":3,"5":4,"6":5,"7":6,"8":7,"9":9,"10":10,"11":11,"12":13},"statementBundles":{"8":{"startLine":7,"endLine":8},"11":{"startLine":11,"endLine":12}},"alternateStyles":{"close-to-source":{"code":"const result = [];\nconst stack = [];\nlet current = root;\nwhile (current != null) {\n    while (current != null) {\n        stack.push(current);\n        current = current.left;\n    }\n    const poppedValue = stack.pop();\n    if (poppedValue === undefined) throw new Error(\"IndexError\");\n    current = poppedValue;\n    result.push(current.val);\n    current = current.right;\n}\nreturn result;","lineMap":{"2":1,"3":2,"4":3,"5":4,"6":5,"7":6,"8":7,"9":9,"10":12,"11":13,"12":15},"statementBundles":{"8":{"startLine":7,"endLine":8},"9":{"startLine":9,"endLine":11},"11":{"startLine":13,"endLine":14}}}}},"typescript":{"languageLabel":"TypeScript","editorLanguage":"typescript","codeStyle":"natural","code":"const result: Array<number> = [];\nconst stack: Array<TreeNode> = [];\nlet current = root;\nwhile (current != null) {\n    while (current != null) {\n        stack.push(current);\n        current = current.left;\n    }\n    current = stack.pop()!;\n    result.push(current.val);\n    current = current.right;\n}\nreturn result;","lineMap":{"2":1,"3":2,"4":3,"5":4,"6":5,"7":6,"8":7,"9":9,"10":10,"11":11,"12":13},"statementBundles":{"8":{"startLine":7,"endLine":8},"11":{"startLine":11,"endLine":12}},"alternateStyles":{"close-to-source":{"code":"const result: Array<number> = [];\nconst stack: Array<TreeNode> = [];\nlet current = root;\nwhile (current != null) {\n    while (current != null) {\n        stack.push(current);\n        current = current.left;\n    }\n    const poppedValue = stack.pop();\n    if (poppedValue === undefined) throw new Error(\"IndexError\");\n    current = poppedValue;\n    result.push(current.val);\n    current = current.right;\n}\nreturn result;","lineMap":{"2":1,"3":2,"4":3,"5":4,"6":5,"7":6,"8":7,"9":9,"10":12,"11":13,"12":15},"statementBundles":{"8":{"startLine":7,"endLine":8},"9":{"startLine":9,"endLine":11},"11":{"startLine":13,"endLine":14}}}}},"java":{"languageLabel":"Java","editorLanguage":"java","codeStyle":"natural","code":"List<Integer> result = new ArrayList<>();\nList<TreeNode> stack = new ArrayList<TreeNode>();\nTreeNode current = root;\nwhile (current != null) {\n    while (current != null) {\n        stack.add(current);\n        current = current.left;\n    }\n    current = stack.remove(stack.size() - 1);\n    result.add(current.val);\n    current = current.right;\n}\nreturn result;","lineMap":{"2":1,"3":2,"4":3,"5":4,"6":5,"7":6,"8":7,"9":9,"10":10,"11":11,"12":13},"statementBundles":{"8":{"startLine":7,"endLine":8},"11":{"startLine":11,"endLine":12}}},"csharp":{"languageLabel":"C#","editorLanguage":"csharp","codeStyle":"natural","code":"List<int> result = new();\nList<TreeNode> stack = new();\nTreeNode current = root;\nwhile (current != null) {\n    while (current != null) {\n        stack.Add(current);\n        current = current.left;\n    }\n    current = stack[stack.Count - 1];\n    stack.RemoveAt(stack.Count - 1);\n    result.Add(current.val);\n    current = current.right;\n}\nreturn result;","lineMap":{"2":1,"3":2,"4":3,"5":4,"6":5,"7":6,"8":7,"9":9,"10":11,"11":12,"12":14},"statementBundles":{"8":{"startLine":7,"endLine":8},"9":{"startLine":9,"endLine":10},"11":{"startLine":12,"endLine":13}}},"cpp":{"languageLabel":"C++","editorLanguage":"cpp","codeStyle":"natural","code":"vector<int> result;\nvector<TreeNode*> stack_;\nTreeNode* current = root;\nwhile (current) {\n    while (current) {\n        stack_.push_back(current);\n        current = current->left;\n    }\n    current = stack_.back();\n    stack_.pop_back();\n    result.push_back(current->val);\n    current = current->right;\n}\nreturn result;","lineMap":{"2":1,"3":2,"4":3,"5":4,"6":5,"7":6,"8":7,"9":9,"10":11,"11":12,"12":14},"statementBundles":{"8":{"startLine":7,"endLine":8},"9":{"startLine":9,"endLine":10},"11":{"startLine":12,"endLine":13}}}}}},{"id":"edge-case-intro","chapter":"Edge cases","kind":"info","eyebrow":"Try to break it","title":"Which inputs could break this?","ctaLabel":"Check edge cases","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"edge-baseline","state":{"tree":[3,2,null,1],"stack":[]}}]},"body":["Two shapes deserve pressure: an empty tree, and a tree that is one long chain down a single side.","These two inputs test whether the same loop rule still holds, or whether either shape forces an extra branch."]},{"id":"empty-probe","chapter":"Edge cases","kind":"case-probe","eyebrow":"Force a decision","title":"What does the loop do when the tree is empty?","workspacePanel":"visualizer","summary":"root is null, so the cursor starts empty and the stack starts empty.","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"empty-baseline","state":{"stack":[],"arrays":[{"name":"result","values":[]}]}}]},"options":[{"id":"never-runs","label":"The loop never runs, and the empty result is returned","rationale":"The guard needs a current node or a non-empty stack; with neither, the body is skipped and the empty list is the answer.","isCorrect":true},{"id":"crash","label":"It crashes trying to read the root's left child","rationale":"The guard is checked before any descent, so an empty cursor never dereferences a missing node.","isCorrect":false},{"id":"needs-guard","label":"A separate empty-tree check has to run first","rationale":"The loop guard already covers it: an empty cursor and an empty stack make the condition false immediately.","isCorrect":false}],"answer":"The loop guard is false from the start, so the body never runs and the empty result is returned as-is."},{"id":"left-chain-probe","chapter":"Edge cases","kind":"case-probe","eyebrow":"Stress the rule","title":"For a left-only chain, what order do the values come out?","workspacePanel":"visualizer","summary":"Each node is the left child of the one above: 1 hangs under 2, which hangs under 3.","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"left-chain","state":{"tree":[3,2,null,1],"node":3}}]},"options":[{"id":"deepest-first","label":"Deepest-first: 1, then 2, then 3","rationale":"The whole spine is pushed before anything pops, so the deepest left node is recorded first and the root last.","isCorrect":true},{"id":"root-first","label":"Root-first: 3, then 2, then 1","rationale":"The root waits on the bottom of the stack until its entire left subtree is recorded, so it comes out last.","isCorrect":false},{"id":"unchanged","label":"Unchanged: there is nothing on the right to interleave","rationale":"Even with no right children, the left-then-node order still reverses the descent order of a left chain.","isCorrect":false}],"answer":"Deepest-first. The spine is pushed top to bottom, then popped bottom to top, so a left chain reads out reversed."},{"id":"ready-to-code","chapter":"Code","kind":"info","eyebrow":"Get ready to code","title":"Turn the rule into code","summary":"The catch: a node is recorded on the pop, never on the push.","ctaLabel":"Start coding","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"ready","state":{"tree":[1,null,2,null,null,3],"node":0}}]},"body":["Loop while either current or the stack still has work. Each round, push current down the left until it runs out, then pop the top node, record its value, and turn current to that node's right child. When both run dry, return what you collected."]},{"id":"coding","chapter":"Code","kind":"coding","source":"coding-checkpoints","eyebrow":"Code the rule","title":"Build the inorder walk","summary":"Now write it: set up the result, stack, and cursor, push each node down the left until it runs out, then pop the top node to record its value and turn the cursor right, and when both the cursor and stack run dry return what you collected.","workspacePanel":"code"},{"id":"complete","chapter":"Code","kind":"complete","eyebrow":"Take it with you","title":"What to carry forward","workspacePanel":"code","body":["The stack made the call stack visible: it holds exactly the nodes you have passed going down-left and still owe a visit.","Inorder is the same as preorder in structure; the one decision that separates them is when you record a node, on the way down or on the way back."],"takeaways":[{"title":"Push down, pop to record","body":"Walk the left spine pushing each node, then pop to record and turn right; the stack remembers the ancestors still owed a visit."},{"title":"Record after the pop","body":"A node is recorded only after its left subtree is done, so the append happens at the pop; appending on the push gives preorder."},{"title":"The loop guard carries the edges","body":"Continuing while current or the stack is non-empty handles the empty tree and the one-sided chain with no extra branch."}],"nextAction":"Submit when you are ready. TraceCode will run the final checks against the code you wrote."}],"slidesOrigin":"authored"},"executionStyle":"solution-method"}
