VOOZH about

URL: https://www.geeksforgeeks.org/dsa/print-ancestors-of-a-given-node-in-binary-tree/

⇱ Print Ancestors of a given node in Binary Tree - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Print Ancestors of a given node in Binary Tree

Last Updated : 25 Apr, 2026

Given a binary tree and a key, the task is to print all ancestors of the node with the given key.

Example:

Input: Key node = 7

👁 blobid0_1777096989

Output: 4 2 1

[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.


Output
4 2 1 

Time Complexity: O(n)
Auxiliary Space: O(h)

Comment
Article Tags:
Article Tags: