1. DFS with Depth Index Tracking
Intuition
Call dfs(root, 0). If level == ans.size(), append a new empty level list. Append node.val to ans[level]. Recurse left and right with level + 1.
When to apply: When recursive solution is preferred over queue BFS.
Algorithm
- Step 1: If root == null, return [].
- Step 2: Define dfs(node, depth):
- - If depth == ans.size(), ans.push([]).
- - ans[depth].push(node.val).
- - If node.left: dfs(node.left, depth + 1).
- - If node.right: dfs(node.right, depth + 1).
- Step 3: Call dfs(root, 0) and return ans.
#include <iostream>#include <vector>#include <string>#include <algorithm>using namespace std; class Solution {public: void dfs(TreeNode* node, int depth, vector<vector<int>>& ans) { if (!node) return; if (depth == (int)ans.size()) ans.push_back({}); ans[depth].push_back(node->val); dfs(node->left, depth + 1, ans); dfs(node->right, depth + 1, ans); } vector<vector<int>> levelOrder(TreeNode* root) { vector<vector<int>> ans; dfs(root, 0, 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.