[Naive Approach] Pre-Order Recursion O(n) time and O(h) space
The core idea involves a recursive pre-order traversal of the binary tree. The function should return true if the current node's value matches the key. For each parent node, if either its left or right child returns true, the parent's value should be added to the result list.
Output
4 2 1
Time Complexity: O(n) Auxiliary Space: O(h)
[Expected Approach] Post-Order Stack based Recursion O(n) time and O(h) space
The approach involves an iterative post-order traversal using a stack to track the path. When the target node is found, the remaining nodes in the stack represent its ancestors.
Note: While the overall Big O time complexity might be the same, this approach is faster due to early pruning and better space handling.