Binary Tree Inorder Traversal
Problem
Given the root of a binary tree, return the values of its nodes in inorder: left subtree, then the node, then right subtree. Try to do it both recursively and with an explicit stack.
Examples
Constraints
- • 0 <= number of nodes <= 100
- • -100 <= Node.val <= 100
Hints & approach
Hint 1
The recursive version is three lines: recurse left, record, recurse right.
Hint 2
To go iterative, simulate the call stack: keep pushing left children until you hit null.
Hint 3
When you pop a node, record it, then move to its right child and repeat the push-left loop.
Approachtry the hints first
Use a stack and a cursor starting at the root. While the cursor is non-null, push it and step to its left child. When the cursor becomes null, pop the top node, append its value, and move the cursor to that node's right child. Repeat until both the stack is empty and the cursor is null. Each node is pushed and popped exactly once.
Time O(n) · Space O(h)