K-th ancestor of a node in Binary Tree | Set 3
Given a binary tree in which nodes are numbered from 1 to N. Given a node and a positive integer K. We have to print the Kth ancestor of the given node in the binary tree. If there does not exist any such ancestor then print -1.
For example in the below given binary tree, 2nd ancestor of node 4 and 5 is 1. 3rd ancestor of node 4 will be -1.

Approach: First we find the path of given key data from the root and we will store it into a vector then we simply return the kth index of the vector from the last.
Below is the implementation of the above approach:
C++
// C++ implementation of the approach#include <bits/stdc++.h>using namespace std;// Structure of Treestruct node { node *left, *right; int data;};// To create a new nodenode* newNode(int data){ node* temp = new node; temp->left = temp->right = NULL; temp->data = data; return temp;}// Function to find the path from// root to the target nodebool RootToNode(node* root, int key, vector<int>& v){ if (root == NULL) return false; // Add current node to the path v.push_back(root->data); // If current node is the target node if (root->data == key) return true; // If the target node exists in // the left or the right sub-tree if (RootToNode(root->left, key, v) || RootToNode(root->right, key, v)) return true; // Remove the last inserted node as // it is not a part of the path // from root to target v.pop_back(); return false;}// Driver codeint main(){ struct node* root = newNode(1); root->left = newNode(2); root->right = newNode(3); root->left->left = newNode(4); root->left->right = newNode(5); root->right->left = newNode(6); root->right->right = newNode(7); // Given node int target = 4; // Vector to store the path from // root to the given node vector<int> v; // Find the path from root to the target node RootToNode(root, target, v); int k = 2; // Print the Kth ancestor if (k > v.size() - 1 || k <= 0) cout << -1; else cout << v[v.size() - 1 - k];} |
Java
// Java implementation of the approachimport java.util.*;class GFG{// Structure of Treestatic class node{ node left, right; int data;};// To create a new nodestatic node newNode(int data){ node temp = new node(); temp.left = temp.right = null; temp.data = data; return temp;}// Function to find the path from// root to the target nodestatic boolean RootToNode(node root, int key, Vector<Integer> v){ if (root == null) return false; // Add current node to the path v.add(root.data); // If current node is the target node if (root.data == key) return true; // If the target node exists in // the left or the right sub-tree if (RootToNode(root.left, key, v) || RootToNode(root.right, key, v)) return true; // Remove the last inserted node as // it is not a part of the path // from root to target v.removeElementAt(v.size()-1); return false;}// Driver codepublic static void main(String[] args){ node root = newNode(1); root.left = newNode(2); root.right = newNode(3); root.left.left = newNode(4); root.left.right = newNode(5); root.right.left = newNode(6); root.right.right = newNode(7); // Given node int target = 4; // Vector to store the path from // root to the given node Vector<Integer> v = new Vector<>(); // Find the path from root to the target node RootToNode(root, target, v); int k = 2; // Print the Kth ancestor if (k > v.size() - 1 || k <= 0) System.out.println(-1); else System.out.println(v.get(v.size() - 1 - k));}}// This code is contributed by Princi Singh |
Python3
# Python3 implementation of the approach# To create a nodeclass Node: def __init__(self, data): self.data = data self.left = None self.right = None# Function to find the path# from root to the target nodedef RootToNode(root, key, v): if root == None: return False # Add current node to the path v.append(root.data) # If current node is the target node if root.data == key: return True # If the target node exists in # the left or the right sub-tree if (RootToNode(root.left, key, v) or RootToNode(root.right, key, v)): return True # Remove the last inserted node # as it is not a part of the # path from root to target v.pop() return False # Driver codeif __name__ == "__main__": root = Node(1) root.left = Node(2) root.right = Node(3) root.left.left = Node(4) root.left.right = Node(5) root.right.left = Node(6) root.right.right = Node(7) # Given node target, k = 4, 2 # Vector to store the path # from root to the given node v = [] # Find the path from root to the target node RootToNode(root, target, v) # Print the Kth ancestor if k > len(v) - 1 or k <= 0: print(-1) else: print(v[len(v) - 1 - k])# This code is contributed by Rituraj Jain |
C#
// C# implementation of above approachusing System.Collections.Generic;using System;class GFG{// Structure of Treepublic class node{ public node left, right; public int data;};// To create a new nodestatic node newNode(int data){ node temp = new node(); temp.left = temp.right = null; temp.data = data; return temp;}// Function to find the path from// root to the target nodestatic bool RootToNode(node root, int key, List<int> v){ if (root == null) return false; // Add current node to the path v.Add(root.data); // If current node is the target node if (root.data == key) return true; // If the target node exists in // the left or the right sub-tree if (RootToNode(root.left, key, v) || RootToNode(root.right, key, v)) return true; // Remove the last inserted node as // it is not a part of the path // from root to target v.Remove(v.Count-1); return false;}// Driver codepublic static void Main(String[] args){ node root = newNode(1); root.left = newNode(2); root.right = newNode(3); root.left.left = newNode(4); root.left.right = newNode(5); root.right.left = newNode(6); root.right.right = newNode(7); // Given node int target = 4; // Vector to store the path from // root to the given node List<int> v = new List<int>(); // Find the path from root to the target node RootToNode(root, target, v); int k = 2; // Print the Kth ancestor if (k > v.Count - 1 || k <= 0) Console.WriteLine(-1); else Console.WriteLine(v[v.Count - 1 - k]);}}// This code is contributed by 29AjayKumar |
Javascript
<script>// JavaScript implementation of above approach// Structure of Treeclass node{ constructor() { this.left = null; this.right = null; this.data = 0; }};// To create a new nodefunction newNode(data){ var temp = new node(); temp.left = temp.right = null; temp.data = data; return temp;}// Function to find the path from// root to the target nodefunction RootToNode(root, key, v){ if (root == null) return false; // push current node to the path v.push(root.data); // If current node is the target node if (root.data == key) return true; // If the target node exists in // the left or the right sub-tree if (RootToNode(root.left, key, v) || RootToNode(root.right, key, v)) return true; // Remove the last inserted node as // it is not a part of the path // from root to target v.pop(); return false;}// Driver codevar root = newNode(1);root.left = newNode(2);root.right = newNode(3);root.left.left = newNode(4);root.left.right = newNode(5);root.right.left = newNode(6);root.right.right = newNode(7);// Given nodevar target = 4;// Vector to store the path from// root to the given nodevar v = [];// Find the path from root to the target nodeRootToNode(root, target, v);var k = 2;// Print the Kth ancestorif (k > v.length - 1 || k <= 0) document.write(-1);else document.write(v[v.length - 1 - k]);</script> |
Output:
1





Please Login to comment...