We are asked to return the inorder traversal of a binary tree.
- Inorder traversal means: Left → Node → Right.
- The simplest way is to use DFS recursion:
- Visit the left subtree
- Process the current node
- Visit the right subtree
-
Define a helper function
dfsInorder(node, res)- If
nodeisnullptr, just return. - Otherwise:
- Recurse on
node->left. - Push
node->valinto result. - Recurse on
node->right.
- Recurse on
- If
-
Call helper starting from
rootwith an empty result vector. -
Return result when traversal is finished.
- Inorder traversal of a BST will naturally give elements in sorted order.
- This solution is recursive, very clean and intuitive.
- Could also be solved iteratively with a stack to simulate recursion.
- Time:
O(n)→ we visit each node once. - Space:
O(n)in worst case recursion stack (for a skewed tree).O(h)in general, wherehis tree height.