Binary Tree Inorder Traversal
Problem Statement:β
Given theΒ rootΒ of a binary tree, returnΒ the inorder traversal of its nodes' values.
Example 1:
Input:Β root = [1,null,2,3]
Output:Β [1,3,2]
Explanation:

-
Example:
β Solution 1: Recursive Inorder Traversalβ
class Solution {
public:
void inOrd(TreeNode *root, vector<int> &res){
if(root == NULL) return;
inOrd(root->left, res); // Traverse left subtree
res.push_back(root->val); // Visit root
inOrd(root->right, res); // Traverse right subtree
}
vector<int> inorderTraversal(TreeNode* root) {
vector<int> res;
inOrd(root, res);
return res;
}
};
β Solution 2: Iterative Inorder Traversal (Using Stack)β
class Solution {
public:
vector<int> inorderTraversal(TreeNode* root) {
vector<int> res;
stack<TreeNode*> st;
TreeNode *curr = root;
while(curr != NULL || !st.empty()){
while(curr != NULL){
st.push(curr); // Go as left as possible
curr = curr->left;
}
curr = st.top(); // Backtrack
st.pop();
res.push_back(curr->val); // Visit the node
curr = curr->right; // Now go to right subtree
}
return res;
}
};
π How It Worksβ
Recursive:β
- Uses the natural recursive structure of trees.
- Traverses in Left β Root β Right order.
- Uses the function call stack implicitly.
Iterative:β
- Uses a manual stack to simulate recursion.
- Repeatedly pushes left children to stack until reaching NULL.
- Then processes node and moves to the right child.
π§© Key Order Ruleβ
Inorder Traversal = [ Left, Root, Right ]
This is particularly useful in Binary Search Trees, where inorder gives sorted order.
β±οΈ Time & Space Complexityβ
| Approach | Time | Space |
|---|---|---|
| Recursive | O(n) | O(h) β call stack (height of tree) |
| Iterative | O(n) | O(h) β stack for traversal |
In worst case (skewed tree), space is O(n).
β οΈ Edge Casesβ
- β Empty tree β returns empty vector
- β Tree with one node β returns single-element vector
- β Left-skewed tree β stack grows linearly
- β Right-skewed tree β same behavior
π‘ Other Approachesβ
| Approach | Time | Space | Notes |
|---|---|---|---|
| Morris Inorder Traversal | O(n) | O(1) | Uses threaded binary trees, modifies structure temporarily |
π Related Problemsβ
- LeetCode 94. Binary Tree Inorder Traversal
- LeetCode 144. Preorder Traversal
- LeetCode 145. Postorder Traversal
- LeetCode 230. Kth Smallest Element in BST
π¬