1. Recursive DFS Inorder Traversal
Intuition
Recursively traverse left subtree, append current node value to result, then recursively traverse right subtree.
When to apply: Default standard implementation in most coding problems.
Algorithm
- Step 1: If root is null, return.
- Step 2: Recursively call dfs(root.left).
- Step 3: Append root.val to result.
- Step 4: Recursively call dfs(root.right).
- Step 5: Return result.
#include <iostream>#include <vector>#include <string>#include <algorithm>using namespace std; class Solution {public: void dfs(TreeNode* root, vector<int>& ans) { if (!root) return; dfs(root->left, ans); ans.push_back(root->val); dfs(root->right, ans); } vector<int> inorderTraversal(TreeNode* root) { vector<int> ans; dfs(root, ans); return ans; }}; int main() { // Sample driver execution cout << "Execution completed successfully." << endl; return 0;} Time & Space Complexity
- Time complexity:
O(n)— Visits each node once in O(n) time. - Space complexity:
O(h)— Call stack takes O(h) space.