Open In App

Iterative method to find ancestors of a given binary tree

Last Updated : 18 Sep, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Given a binary tree, print all the ancestors of a particular key existing in the tree without using recursion.
Here we will be discussing the implementation for the above problem. 

Examples: 

Input : 
            1
        /       \
       2         7
     /   \     /   \
    3     5    8    9 
   /       \       /
  4         6     10 
Key = 6 

Output : 5 2 1
Ancestors of 6 are 5, 2 and 1.

The idea is to use iterative postorder traversal of given binary tree.  

Algorithm:

Step 1: Start
Step 2: create a function of void return type called “printAncestors” which takes a root node and an integer value as input                          parameter.
             a. set the base condition as if root == null then return.
             b. create a stack of node types to hold ancestors
             c. start a while loop with condition 1==1 which means it will always be true.
                 1. Move each node into the stack by moving them up and along the left side of the tree starting at the root until we                            reach the node that matches the key. 
                 2. End the while loop if the node with the specified key is located.
                 3. Remove the node from the stack and assign it to the root if the right subtree of the node at the top of the stack, st, is                       null.
                 4. Pop that node as well if it is the right child of the node at the top of the stack, st.
                 5. Set root as the right child of the node at the top of the stack st if it is not empty and carry on exploring the right                               subtree.
Step 3: If the stack st is not empty when we have located the node with the specified key, print the data of each node in the stack              st starting at the top and continuing until the stack is empty.
Step 4: End

Implementation:

C++




// C++ program to print all ancestors of a given key
#include <bits/stdc++.h>
using namespace std;
  
// Structure for a tree node
struct Node {
    int data;
    struct Node* left, *right;
};
  
// A utility function to create a new tree node
struct Node* newNode(int data)
{
    struct Node* node = (struct Node*)malloc(sizeof(struct Node));
    node->data = data;
    node->left = node->right = NULL;
    return node;
}
  
// Iterative Function to print all ancestors of a
// given key
void printAncestors(struct Node* root, int key)
{
    if (root == NULL)
        return;
  
    // Create a stack to hold ancestors
    stack<struct Node*> st;
  
    // Traverse the complete tree in postorder way till
    // we find the key
    while (1) {
  
        // Traverse the left side. While traversing, push
        // the nodes into  the stack so that their right
        // subtrees can be traversed later
        while (root && root->data != key) {
            st.push(root); // push current node
            root = root->left; // move to next node
        }
  
        // If the node whose ancestors are to be printed
        // is found, then break the while loop.
        if (root && root->data == key)
            break;
  
        // Check if right sub-tree exists for the node at top
        // If not then pop that node because we don't need
        // this node any more.
        if (st.top()->right == NULL) {
            root = st.top();
            st.pop();
  
            // If the popped node is right child of top,
            // then remove the top as well. Left child of
            // the top must have processed before.
            while (!st.empty() && st.top()->right == root) {
                root = st.top();
                st.pop();
            }
        }
  
        // if stack is not empty then simply set the root
        // as right child of top and start traversing right
        // sub-tree.
        root = st.empty() ? NULL : st.top()->right;
    }
  
    // If stack is not empty, print contents of stack
    // Here assumption is that the key is there in tree
    while (!st.empty()) {
        cout << st.top()->data << " ";
        st.pop();
    }
}
  
// Driver program to test above functions
int main()
{
    // Let us construct a binary tree
    struct Node* root = newNode(1);
    root->left = newNode(2);
    root->right = newNode(7);
    root->left->left = newNode(3);
    root->left->right = newNode(5);
    root->right->left = newNode(8);
    root->right->right = newNode(9);
    root->left->left->left = newNode(4);
    root->left->right->right = newNode(6);
    root->right->right->left = newNode(10);
  
    int key = 6;
    printAncestors(root, key);
  
    return 0;
}


Java




// Java program to print all 
// ancestors of a given key 
import java.util.*;
  
class GfG 
{
  
// Structure for a tree node 
static class Node
    int data; 
    Node left, right; 
}
  
// A utility function to 
// create a new tree node 
static Node newNode(int data) 
    Node node = new Node(); 
    node.data = data; 
    node.left = null;
    node.right = null
    return node; 
  
// Iterative Function to print 
// all ancestors of a given key 
static void printAncestors(Node root, int key) 
    if (root == null
        return
  
    // Create a stack to hold ancestors 
    Stack<Node> st = new Stack<Node> (); 
  
    // Traverse the complete tree in 
    // postorder way till we find the key 
    while (1 == 1
    
  
        // Traverse the left side. While 
        // traversing, push the nodes into 
        // the stack so that their right 
        // subtrees can be traversed later 
        while (root != null && root.data != key) 
        
            st.push(root); // push current node 
            root = root.left; // move to next node 
        
  
        // If the node whose ancestors 
        // are to be printed is found,
        // then break the while loop. 
        if (root != null && root.data == key) 
            break
  
        // Check if right sub-tree exists
        // for the node at top If not then
        // pop that node because we don't  
        // need this node any more. 
        if (st.peek().right == null
        
            root = st.peek(); 
            st.pop(); 
  
            // If the popped node is right child of top, 
            // then remove the top as well. Left child of 
            // the top must have processed before. 
            while (!st.isEmpty() && st.peek().right == root)
            
                root = st.peek(); 
                st.pop(); 
            
        
  
        // if stack is not empty then simply 
        // set the root as right child of 
        // top and start traversing right 
        // sub-tree. 
        root = st.isEmpty() ? null : st.peek().right; 
    
  
    // If stack is not empty, print contents of stack 
    // Here assumption is that the key is there in tree 
    while (!st.isEmpty())
    
        System.out.print(st.peek().data + " "); 
        st.pop(); 
    
  
// Driver code 
public static void main(String[] args) 
    // Let us construct a binary tree 
    Node root = newNode(1); 
    root.left = newNode(2); 
    root.right = newNode(7); 
    root.left.left = newNode(3); 
    root.left.right = newNode(5); 
    root.right.left = newNode(8); 
    root.right.right = newNode(9); 
    root.left.left.left = newNode(4); 
    root.left.right.right = newNode(6); 
    root.right.right.left = newNode(10); 
  
    int key = 6
    printAncestors(root, key); 
}
}
  
// This code is contributed 
// by prerna saini


Python3




# Python program to print all ancestors of a given key
  
# A class to create a new tree node 
class newNode:
    def __init__(self, data):
        self.data = data 
        self.left = self.right = None
  
# Iterative Function to print all ancestors of a 
# given key 
def printAncestors(root, key):
    if (root == None): 
        return
  
    # Create a stack to hold ancestors 
    st = []
  
    # Traverse the complete tree in postorder way till 
    # we find the key 
    while (1):
  
        # Traverse the left side. While traversing, push 
        # the nodes into the stack so that their right 
        # subtrees can be traversed later 
        while (root and root.data != key): 
            st.append(root) # push current node 
            root = root.left # move to next node
  
        # If the node whose ancestors are to be printed 
        # is found, then break the while loop. 
        if (root and root.data == key): 
            break
  
        # Check if right sub-tree exists for the node at top 
        # If not then pop that node because we don't need 
        # this node any more. 
        if (st[-1].right == None): 
            root = st[-1
            st.pop() 
  
            # If the popped node is right child of top, 
            # then remove the top as well. Left child of 
            # the top must have processed before. 
            while (len(st) != 0 and st[-1].right == root): 
                root = st[-1
                st.pop()
  
        # if stack is not empty then simply set the root 
        # as right child of top and start traversing right 
        # sub-tree. 
        root = None if len(st) == 0 else st[-1].right
  
    # If stack is not empty, print contents of stack 
    # Here assumption is that the key is there in tree 
    while (len(st) != 0): 
        print(st[-1].data,end = " "
        st.pop()
  
# Driver code
if __name__ == '__main__':
  
    # Let us construct a binary tree 
    root = newNode(1
    root.left = newNode(2
    root.right = newNode(7
    root.left.left = newNode(3
    root.left.right = newNode(5
    root.right.left = newNode(8
    root.right.right = newNode(9
    root.left.left.left = newNode(4
    root.left.right.right = newNode(6
    root.right.right.left = newNode(10
  
    key = 6
    printAncestors(root, key)
      
# This code is contributed by PranchalK.


C#




// C# program to print all 
// ancestors of a given key 
using System;
using System.Collections.Generic;
  
class GfG 
{
  
// Structure for a tree node 
public class Node
    public int data; 
    public Node left, right; 
}
  
// A utility function to 
// create a new tree node 
static Node newNode(int data) 
    Node node = new Node(); 
    node.data = data; 
    node.left = null;
    node.right = null
    return node; 
  
// Iterative Function to print 
// all ancestors of a given key 
static void printAncestors(Node root, int key) 
    if (root == null
        return
  
    // Create a stack to hold ancestors 
    Stack<Node> st = new Stack<Node> (); 
  
    // Traverse the complete tree in 
    // postorder way till we find the key 
    while (1 == 1) 
    
  
        // Traverse the left side. While 
        // traversing, push the nodes into 
        // the stack so that their right 
        // subtrees can be traversed later 
        while (root != null && root.data != key) 
        
            st.Push(root); // push current node 
            root = root.left; // move to next node 
        
  
        // If the node whose ancestors 
        // are to be printed is found,
        // then break the while loop. 
        if (root != null && root.data == key) 
            break
  
        // Check if right sub-tree exists
        // for the node at top If not then
        // pop that node because we don't 
        // need this node any more. 
        if (st.Peek().right == null
        
            root = st.Peek(); 
            st.Pop(); 
  
            // If the popped node is right child of top, 
            // then remove the top as well. Left child of 
            // the top must have processed before. 
            while (st.Count != 0 && st.Peek().right == root)
            
                root = st.Peek(); 
                st.Pop(); 
            
        
  
        // if stack is not empty then simply 
        // set the root as right child of 
        // top and start traversing right 
        // sub-tree. 
        root = st.Count == 0 ? null : st.Peek().right; 
    
  
    // If stack is not empty, print contents of stack 
    // Here assumption is that the key is there in tree 
    while (st.Count != 0)
    
        Console.Write(st.Peek().data + " "); 
        st.Pop(); 
    
  
// Driver code 
public static void Main(String[] args) 
    // Let us construct a binary tree 
    Node root = newNode(1); 
    root.left = newNode(2); 
    root.right = newNode(7); 
    root.left.left = newNode(3); 
    root.left.right = newNode(5); 
    root.right.left = newNode(8); 
    root.right.right = newNode(9); 
    root.left.left.left = newNode(4); 
    root.left.right.right = newNode(6); 
    root.right.right.left = newNode(10); 
  
    int key = 6; 
    printAncestors(root, key); 
}
}
  
// This code has been contributed by 29AjayKumar


Javascript




<script>
  
// Javascript program to print all 
// ancestors of a given key 
class Node
{
    constructor(data) 
    {
        this.left = null;
        this.right = null;
        this.data = data;
    }
}
  
// A utility function to 
// create a new tree node 
function newNode(data) 
    let node = new Node(data); 
    return node; 
  
// Iterative Function to print 
// all ancestors of a given key 
function printAncestors(root, key) 
    if (root == null
        return
  
    // Create a stack to hold ancestors 
    let st = []; 
  
    // Traverse the complete tree in 
    // postorder way till we find the key 
    while (1 == 1) 
    {
          
        // Traverse the left side. While 
        // traversing, push the nodes into 
        // the stack so that their right 
        // subtrees can be traversed later 
        while (root != null && root.data != key) 
        
              
            // Push current node 
            st.push(root); 
              
            // Move to next node 
            root = root.left; 
        
  
        // If the node whose ancestors 
        // are to be printed is found,
        // then break the while loop. 
        if (root != null && root.data == key) 
            break
  
        // Check if right sub-tree exists
        // for the node at top If not then
        // pop that node because we don't 
        // need this node any more. 
        if (st[st.length - 1].right == null
        
            root = st[st.length - 1]; 
            st.pop(); 
  
            // If the popped node is right child of top, 
            // then remove the top as well. Left child of 
            // the top must have processed before. 
            while (st.length != 0 && 
                st[st.length - 1].right == root)
            
                root = st[st.length - 1]; 
                st.pop(); 
            
        
  
        // If stack is not empty then simply 
        // set the root as right child of 
        // top and start traversing right 
        // sub-tree. 
        root = st.length == 0 ? null
            st[st.length - 1].right; 
    
  
    // If stack is not empty, print contents
    // of stack. Here assumption is that the 
    // key is there in tree 
    while (st.length != 0)
    
        document.write(st[st.length - 1].data + " "); 
        st.pop(); 
    
  
// Driver code
  
// Let us construct a binary tree 
let root = newNode(1); 
root.left = newNode(2); 
root.right = newNode(7); 
root.left.left = newNode(3); 
root.left.right = newNode(5); 
root.right.left = newNode(8); 
root.right.right = newNode(9); 
root.left.left.left = newNode(4); 
root.left.right.right = newNode(6); 
root.right.right.left = newNode(10); 
  
let key = 6; 
printAncestors(root, key); 
  
// This code is contributed by divyeshrabadiya07
  
</script>


Output

5 2 1 

Complexity Analysis:

  • Time Complexity: O(n)
  • Space Complexity: O(n)

 



Previous Article
Next Article

Similar Reads

Print ancestors of a given binary tree node without recursion
Given a Binary Tree and a key, write a function that prints all the ancestors of the key in the given binary tree.For example, consider the following Binary Tree 1 / \ 2 3 / \ / \ 4 5 6 7 / \ / 8 9 10 Following are different input keys and their ancestors in the above tree Input Key List of Ancestors ------------------------- 1 2 1 3 1 4 2 1 5 2 1
15 min read
Print Ancestors of a given node in Binary Tree
Given a Binary Tree and a key, write a function that prints all the ancestors of the key in the given binary tree. For example, if the given tree is following Binary Tree and the key is 7, then your function should print 4, 2, and 1. 1 / \ 2 3 / \ 4 5 / 7Recommended PracticeAncestors in Binary TreeTry It!Thanks to Mike, Sambasiva and wgpshashank fo
13 min read
Find most frequent value of ancestors for each Node of given Tree
Given a tree with N vertices from 0 to N-1 (0th node is root) and val[] where val[i] denotes the value of the ith vertex. The task is to find the array of integers ans[] of length N, where ans[i] denotes the mode value of all its ancestors' values including ith vertex. Note: Mode is the value that has the highest frequency in a given set of values(
10 min read
Check whether a binary tree is a full binary tree or not | Iterative Approach
Given a binary tree containing n nodes. The problem is to check whether the given binary tree is a full binary tree or not. A full binary tree is defined as a binary tree in which all nodes have either zero or two child nodes. Conversely, there is no node in a full binary tree, which has only one child node. Examples: Input : 1 / \ 2 3 / \ 4 5 Outp
8 min read
Check if a binary tree is subtree of another binary tree using preorder traversal : Iterative
Given two binary trees S and T, the task is the check that if S is a subtree of the Tree T. For Example: Input: Tree T - 1 / \ 2 3 / \ / \ 4 5 6 7 Tree S - 2 / \ 4 5 Output: YES Explanation: The above tree is the subtree of the tree T, Hence the output is YES Approach: The idea is to traverse both the tree in Pre-order Traversal and check for each
11 min read
Count ancestors with smaller value for each node of a Binary Tree
Given a Binary Tree consisting of N nodes, valued from 1 to N, rooted at node 1, the task is for each node is to count the number of ancestors with a value smaller than that of the current node. Examples: Input: Below is the given Tree: 1 / \ 4 5 / /\ 6 3 2Output: 0 1 1 1 1 2Explanation: Since node 1 is the root node, it has no ancestors.Ancestors
9 min read
Count the number of common ancestors of given K nodes in a N-ary Tree
Given an N-ary tree root and a list of K nodes, the task is to find the number of common ancestors of the given K nodes in the tree. Example: Input: root = 3 / \ 2 1 / \ / | \ 9 7 8 6 3K = {7, 2, 9}Output: 2 Explanation: The common ancestors of the nodes 7, 9 and 2 are 2 and 3 Input: root = 2 \ 1 \ 0---4 / | \ 9 3 8K = {9, 8, 3, 4, 0}Output: 3 Appr
10 min read
Median of ancestors for each Node of a given tree
Given a tree with N vertices from 0 to N - 1 (0th node is root) and val[] where val[i] denotes the value of the ith vertex, the task is to find the array of integers ans[] of length N, where ans[i] denotes the median value of all its ancestors' values including ith vertex. Points to remember: If number of nodes are even: then median = ((n/2th node
10 min read
Iterative Method to find Height of Binary Tree
There are two conventions to define the height of a Binary Tree Number of nodes on the longest path from the root to the deepest node. Number of edges on the longest path from the root to the deepest node. In this post, the first convention is followed. For example, the height of the below tree is 3. The recursive method to find the height of the B
8 min read
Find ancestors of each node in the given Graph
Given a graph in the form of an edge list and a directed graph, return all the ancestors of the nodes in any order. An ancestor is a node one step ahead in the hierarchy on the same path reachable to the current node.  Note: The graph has no cycle. Examples: Input: N = 5, Edges[][2] = {{0, 4}, {4, 1}, {4, 3}, {1, 2}}Output: Result[N][] = {{}, {0, 4
15 min read
Article Tags :
Practice Tags :