1. All Paths Enumeration to Leaves
Intuition
Recursively traverse to leaves. When reaching a leaf, update minDepth. Return minDepth at the end.
When to apply: Basic baseline check.
Algorithm
- Step 1: If root == null return 0.
- Step 2: Track minDepth initialized to infinity.
- Step 3: In dfs(node, curDepth): if node is leaf, minDepth = min(minDepth, curDepth).
- Step 4: Recurse on children.
- Step 5: Return minDepth.
#include <iostream>#include <vector>#include <string>#include <algorithm>using namespace std; class Solution {public: void dfs(TreeNode* node, int cur, int& minD) { if (!node) return; if (!node->left && !node->right) { minD = min(minD, cur); return; } dfs(node->left, cur + 1, minD); dfs(node->right, cur + 1, minD); } int minDepth(TreeNode* root) { if (!root) return 0; int minD = INT_MAX; dfs(root, 1, minD); return minD; }}; int main() { // Sample driver execution cout << "Execution completed successfully." << endl; return 0;} Time & Space Complexity
- Time complexity:
O(n)— Visits all nodes in the tree. - Space complexity:
O(h)— Call stack takes O(h) space.