1. Path Array Collection
Intuition
Use standard path-finding DFS to store path of node values from root to target. If path.size() <= k, return -1. Otherwise, return path[path.size() - 1 - k].
When to apply: Basic baseline check.
Algorithm
- Step 1: Helper findPath(root, target, path).
- Step 2: If target found, path contains [root ... target].
- Step 3: If path.size() <= k, return -1.
- Step 4: Return path[path.size() - 1 - k].
#include <iostream>#include <vector>#include <string>#include <algorithm>using namespace std; class Solution {public: bool findPath(TreeNode* root, int target, vector<int>& path) { if (!root) return false; path.push_back(root->val); if (root->val == target) return true; if (findPath(root->left, target, path) || findPath(root->right, target, path)) return true; path.pop_back(); return false; } int kthAncestor(TreeNode* root, int k, int node) { vector<int> path; if (!findPath(root, node, path)) return -1; int idx = (int)path.size() - 1 - k; return (idx >= 0) ? path[idx] : -1; }}; int main() { // Sample driver execution cout << "Execution completed successfully." << endl; return 0;} Time & Space Complexity
- Time complexity:
O(n)— DFS searches for target once in O(n). - Space complexity:
O(h)— Path array holds up to h nodes.