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


πŸ’¬

Discussion & Doubts