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

Try It Yourself
redirect icon

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

C++
#include <iostream>
#include <vector>
using namespace std;

class Node
{
  public:
    int data;
    Node *left, *right;
    Node(int x)
    {
        data = x;
        left = nullptr;
        right = nullptr;
    }
};

bool ancestorsRecur(Node *root, int key, vector<int> &res)
{

    // Base Case
    if (root == nullptr)
        return false;

    // If current node is key node
    if (root->data == key)
        return true;

    bool left = ancestorsRecur(root->left, key, res);
    bool right = ancestorsRecur(root->right, key, res);

    // If current node is ancestor to key node
    if (left || right)
        res.push_back(root->data);

    return left || right;
}

vector<int> ancestors(Node *root, int key)
{

    vector<int> res;

    // Perform pre-order traversal
    ancestorsRecur(root, key, res);

    return res;
}

int main()
{

    // Binary tree
    //          1
    //         / \
	//        2   3
    //       / \
	//      4   5
    //     /
    //    7
    Node *root = new Node(1);
    root->left = new Node(2);
    root->right = new Node(3);
    root->left->left = new Node(4);
    root->left->right = new Node(5);
    root->left->left->left = new Node(7);
    int key = 7;

    vector<int> res = ancestors(root, key);
    for (auto val : res)
        cout << val << " ";
    cout << endl;
    return 0;
}
Java
import java.util.ArrayList;

class Node {
    public int data;
    public Node left, right;

    public Node(int x) {
        data = x;
        left = null;
        right = null;
    }
}

public class GFG {
    public static boolean ancestorsRecur(Node root, int key, ArrayList<Integer> res) {
        // Base Case
        if (root == null)
            return false;

        // If current node is key node
        if (root.data == key)
            return true;

        boolean left = ancestorsRecur(root.left, key, res);
        boolean right = ancestorsRecur(root.right, key, res);

        // If current node is ancestor to key node
        if (left || right)
            res.add(root.data);

        return left || right;
    }

    public static ArrayList<Integer> ancestors(Node root, int key) {
        ArrayList<Integer> res = new ArrayList<>();

        // Perform pre-order traversal
        ancestorsRecur(root, key, res);

        return res;
    }

    public static void main(String[] args) {
        // Binary tree
        //          1
        //         / \
        //        2   3
        //       / \
        //      4   5
        //     /
        //    7
        Node root = new Node(1);
        root.left = new Node(2);
        root.right = new Node(3);
        root.left.left = new Node(4);
        root.left.right = new Node(5);
        root.left.left.left = new Node(7);
        int key = 7;

        ArrayList<Integer> res = ancestors(root, key);
        for (int val : res)
            System.out.print(val + " ");
        System.out.println();
    }
}
Python
class Node:
    def __init__(self, x):
        self.data = x
        self.left = None
        self.right = None

def ancestors_recur(root, key, res):
    # Base Case
    if root is None:
        return False

    # If current node is key node
    if root.data == key:
        return True

    left = ancestors_recur(root.left, key, res)
    right = ancestors_recur(root.right, key, res)

    # If current node is ancestor to key node
    if left or right:
        res.append(root.data)

    return left or right

def ancestors(root, key):
    res = []

    # Perform pre-order traversal
    ancestors_recur(root, key, res)

    return res

if __name__ == '__main__':
    # Binary tree
    #          1
    #         / \
    #        2   3
    #       / \
    #      4   5
    #     /
    #    7
    root = Node(1)
    root.left = Node(2)
    root.right = Node(3)
    root.left.left = Node(4)
    root.left.right = Node(5)
    root.left.left.left = Node(7)
    key = 7

    res = ancestors(root, key)
    for val in res:
        print(val, end=' ')
    print()
C#
using System;
using System.Collections.Generic;

public class Node
{
    public int data;
    public Node left, right;

    public Node(int x)
    {
        data = x;
        left = null;
        right = null;
    }
}

public class GFG
{
    public static bool AncestorsRecur(Node root, int key, List<int> res)
    {
        // Base Case
        if (root == null)
            return false;

        // If current node is key node
        if (root.data == key)
            return true;

        bool left = AncestorsRecur(root.left, key, res);
        bool right = AncestorsRecur(root.right, key, res);

        // If current node is ancestor to key node
        if (left || right)
            res.Add(root.data);

        return left || right;
    }

    public static List<int> Ancestors(Node root, int key)
    {
        List<int> res = new List<int>();

        // Perform pre-order traversal
        AncestorsRecur(root, key, res);

        return res;
    }

    public static void Main()
    {
        // Binary tree
        //          1
        //         / \
        //        2   3
        //       / \
        //      4   5
        //     /
        //    7
        Node root = new Node(1);
        root.left = new Node(2);
        root.right = new Node(3);
        root.left.left = new Node(4);
        root.left.right = new Node(5);
        root.left.left.left = new Node(7);
        int key = 7;

        List<int> res = Ancestors(root, key);
        foreach (int val in res)
            Console.Write(val + " ");
        Console.WriteLine();
    }
}
JavaScript
class Node {
    constructor(x) {
        this.data = x;
        this.left = null;
        this.right = null;
    }
}

function ancestorsRecur(root, key, res) {
    // Base Case
    if (root === null)
        return false;

    // If current node is key node
    if (root.data === key)
        return true;

    let left = ancestorsRecur(root.left, key, res);
    let right = ancestorsRecur(root.right, key, res);

    // If current node is ancestor to key node
    if (left || right)
        res.push(root.data);

    return left || right;
}

function ancestors(root, key) {
    let res = [];

    // Perform pre-order traversal
    ancestorsRecur(root, key, res);

    return res;
}

// Binary tree
//          1
//         / \
//        2   3
//       / \
//      4   5
//     /
//    7
let root = new Node(1);
root.left = new Node(2);
root.right = new Node(3);
root.left.left = new Node(4);
root.left.right = new Node(5);
root.left.left.left = new Node(7);
let key = 7;

let res = ancestors(root, key);
for (let val of res)
    process.stdout.write(val + ' ');
console.log();

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.

C++
#include<iostream>
#include<vector>
#include<stack>
using namespace std;

class Node {
public:
    int data;
    Node* left, *right;
    Node (int x) {
        data = x;
        left = nullptr;
        right = nullptr;
    }
};

vector<int> ancestors(Node* root, int key) {
    vector<int> res;
    if (root == nullptr) return res;
    
    stack<Node*> st;
    Node* curr = root;
    Node* prev = nullptr;
    
    while (curr != nullptr || !st.empty()) {
        if (curr != nullptr) {
            st.push(curr);
            curr = curr->left;
        } 
        else {
            Node* topNode = st.top();
            if (topNode->right != nullptr && prev != topNode->right) {
                curr = topNode->right;
            } else {
                if (topNode->data == key) {
                    
                    // Found the key node, now all nodes
                    // in stack are ancestors
                    st.pop();  
                    while (!st.empty()) {
                        res.push_back(st.top()->data);
                        st.pop();
                    }
                    return res;
                }
                prev = st.top();
                st.pop();
            }
        }
    }
    
    return res;  
}

int main() {
    
    // Binary tree
    //           1
    //         /   \
    //       2      3
    //     /  \
    //   4     5
    //  /
    // 7
    Node *root = new Node(1);
    root->left = new Node(2);
    root->right = new Node(3);
    root->left->left = new Node(4);
    root->left->right = new Node(5);
    root->left->left->left = new Node(7);
    int key = 7;

    vector<int> res = ancestors(root, key);
    for (auto val: res) cout << val << " ";
    cout << endl;
    return 0;
}
Java
import java.util.ArrayList;
import java.util.Stack;

class Node {
    int data;
    Node left, right;
    Node(int x) {
        data = x;
        left = null;
        right = null;
    }
}

class GfG {
    static ArrayList<Integer> ancestors(Node root, int key) {
        ArrayList<Integer> res = new ArrayList<>();
        if (root == null) return res;
        
        Stack<Node> st = new Stack<>();
        Node curr = root;
        Node prev = null;
        
        while (curr != null || !st.empty()) {
            if (curr != null) {
                st.push(curr);
                curr = curr.left;
            } 
            else {
                Node topNode = st.peek();
                if (topNode.right != null && prev != topNode.right) {
                    curr = topNode.right;
                } else {
                    if (topNode.data == key) {
                        
                        // Found the key node, now all nodes
                        // in stack are ancestors
                        st.pop();  
                        while (!st.empty()) {
                            res.add(st.peek().data);
                            st.pop();
                        }
                        return res;
                    }
                    prev = st.peek();
                    st.pop();
                }
            }
        }
        
        return res;  
    }

    public static void main(String[] args) {
        
        // Binary tree
        //           1
        //         /   \
        //       2      3
        //     /  \
        //   4     5
        //  /
        // 7
        Node root = new Node(1);
        root.left = new Node(2);
        root.right = new Node(3);
        root.left.left = new Node(4);
        root.left.right = new Node(5);
        root.left.left.left = new Node(7);
        int key = 7;

        ArrayList<Integer> res = ancestors(root, key);
        for (int val : res) System.out.print(val + " ");
        System.out.println();
    }
}
Python
class Node:
    def __init__(self, x):
        self.data = x
        self.left = None
        self.right = None

def ancestors(root, key):
    res = []
    if root is None:
        return res
    
    st = []
    curr = root
    prev = None
    
    while curr is not None or len(st) > 0:
        if curr is not None:
            st.append(curr)
            curr = curr.left
        else:
            topNode = st[-1]
            if topNode.right is not None and prev != topNode.right:
                curr = topNode.right
            else:
                if topNode.data == key:
                    
                    # Found the key node, now all nodes
                    # in stack are ancestors
                    st.pop()
                    while len(st) > 0:
                        res.append(st[-1].data)
                        st.pop()
                    return res
                prev = st[-1]
                st.pop()
    
    return res

if __name__ == "__main__":
    
    # Binary tree
    #           1
    #         /   \
    #       2      3
    #     /  \
    #   4     5
    #  /
    # 7
    root = Node(1)
    root.left = Node(2)
    root.right = Node(3)
    root.left.left = Node(4)
    root.left.right = Node(5)
    root.left.left.left = Node(7)
    key = 7

    res = ancestors(root, key)
    for val in res:
        print(val, end=" ")
    print()
C#
using System;
using System.Collections.Generic;

class Node {
    public int data;
    public Node left, right;
    public Node(int x) {
        data = x;
        left = null;
        right = null;
    }
}

class GfG {
    static List<int> ancestors(Node root, int key) {
        List<int> res = new List<int>();
        if (root == null) return res;
        
        Stack<Node> st = new Stack<Node>();
        Node curr = root;
        Node prev = null;
        
        while (curr != null || st.Count > 0) {
            if (curr != null) {
                st.Push(curr);
                curr = curr.left;
            } 
            else {
                Node topNode = st.Peek();
                if (topNode.right != null && prev != topNode.right) {
                    curr = topNode.right;
                } else {
                    if (topNode.data == key) {
                        
                        // Found the key node, now all nodes
                        // in stack are ancestors
                        st.Pop();  
                        while (st.Count > 0) {
                            res.Add(st.Peek().data);
                            st.Pop();
                        }
                        return res;
                    }
                    prev = st.Peek();
                    st.Pop();
                }
            }
        }
        
        return res;  
    }

    static void Main() {
        // Binary tree
        //           1
        //         /   \
        //       2      3
        //     /  \
        //   4     5
        //  /
        // 7
        Node root = new Node(1);
        root.left = new Node(2);
        root.right = new Node(3);
        root.left.left = new Node(4);
        root.left.right = new Node(5);
        root.left.left.left = new Node(7);
        int key = 7;

        List<int> res = ancestors(root, key);
        foreach (int val in res) Console.Write(val + " ");
        Console.WriteLine();
    }
}
JavaScript
class Node {
    constructor(x) {
        this.data = x;
        this.left = null;
        this.right = null;
    }
}

function ancestors(root, key) {
    let res = [];
    if (root === null) return res;
    
    let st = [];
    let curr = root;
    let prev = null;
    
    while (curr !== null || st.length > 0) {
        if (curr !== null) {
            st.push(curr);
            curr = curr.left;
        } 
        else {
            let topNode = st[st.length-1];
            if (topNode.right !== null && prev !== topNode.right) {
                curr = topNode.right;
            } else {
                if (topNode.data === key) {
                    
                    // Found the key node, now all nodes
                    // in stack are ancestors
                    st.pop();  
                    while (st.length > 0) {
                        res.push(st[st.length-1].data);
                        st.pop();
                    }
                    return res;
                }
                prev = st[st.length-1];
                st.pop();
            }
        }
    }
    
    return res;  
}

//Binary tree
//           1
//         /   \
//       2      3
//     /  \
//   4     5
//  /
// 7
let root = new Node(1);
root.left = new Node(2);
root.right = new Node(3);
root.left.left = new Node(4);
root.left.right = new Node(5);
root.left.left.left = new Node(7);
let key = 7;

let res = ancestors(root, key);
console.log(res.join(" "));

Output
4 2 1 

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

Comment