1. Recursive DFS Preorder Traversal
Intuition
Define a recursive helper function that takes the current node. If node is null, return. Append node.val to result. Recursively call helper(node.left), then helper(node.right).
When to apply: Default standard implementation when call stack space is acceptable.
Algorithm
- Step 1: If root is null, return empty list.
- Step 2: Process current node value: append root.val to result.
- Step 3: Recursively traverse left child.
- Step 4: Recursively traverse right child.
- 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; ans.push_back(root->val); dfs(root->left, ans); dfs(root->right, ans); } vector<int> preorderTraversal(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)— Every node is visited exactly once, taking O(n) time. Call stack takes O(h) memory where h is tree height (O(log n) balanced, O(n) worst case). - Space complexity:
O(h)— Recursion call stack takes O(h) space.