Skip to main content

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​

ApproachTimeSpace
RecursiveO(n)O(h) β†’ call stack (height of tree)
IterativeO(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​

ApproachTimeSpaceNotes
Morris Inorder TraversalO(n)O(1)Uses threaded binary trees, modifies structure temporarily


πŸš€ Level Up Your Engineering Mindset

Never Study in Isolation. Join Binary Dose.

Connect with fellow engineers, clear conceptual doubts, and get 2 visual breakdowns & engineering mental models daily across our community channels.

Discord
Official Hub

Discord Community

Start at #welcome-and-rules, say hello in #general-chat, clear doubts, and collaborate with engineers worldwide.

Join Discord Server→
⚑
Daily Knowledge Drops

Daily Visual Deep-Dives

Bite-sized system design schematics, core OS internals, and DSA intuition served right into your feeds every single day.

πŸ’‘Have handwritten notes, cheat-sheets, or want to publish a technical article?
Learn How to Contribute→