1. All Root-to-Leaf Path Collection
Intuition
Find all root-to-leaf paths using backtracking, store their lengths in a list, and find the maximum length.
When to apply: Basic baseline check.
Algorithm
- Step 1: If root == null return 0.
- Step 2: Traverse all paths from root to leaves.
- Step 3: Track path lengths in an array.
- Step 4: Return maximum length found.
#include <iostream>#include <vector>#include <string>#include <algorithm>using namespace std; class Solution {public: void getPaths(TreeNode* node, int cur, int& maxD) { if (!node) return; if (!node->left && !node->right) { maxD = max(maxD, cur + 1); return; } getPaths(node->left, cur + 1, maxD); getPaths(node->right, cur + 1, maxD); } int maxDepth(TreeNode* root) { if (!root) return 0; int maxD = 0; getPaths(root, 0, maxD); return maxD; }}; int main() { // Sample driver execution cout << "Execution completed successfully." << endl; return 0;} Time & Space Complexity
- Time complexity:
O(n)— Visits all nodes and stores path representations. - Space complexity:
O(n)— O(n) memory to store path records.