Ancestor Queries - Google Top Interview Questions


Problem Statement :


Implement a data structure with the following methods:

AncestorQuerier(Tree root) which instantiates the data structure with the given tree node. root only contains unique values

int getAncestor(int val, int k) which returns the kth (0-indexed) ancestor of node with value val. If there's 
no kth ancestor, return -1.

Constraints



0 ≤ n ≤ 100,000 where n is the number of nodes in root

0 ≤ m ≤ 100,000 where m is the number of calls to getAncestor

Example 1

Input

methods = ["constructor", "getAncestor", "getAncestor", "getAncestor"]

arguments = [[[1, [2, [3, null, null], [4, null, null]], null]], [4, 1], [1, 1], [4, 2]]`

Output

[None, 2, -1, 1]



Solution :



title-img




                        Solution in C++ :

*/
class AncestorQuerier {
    unordered_map<int, int> mp;
    vector<vector<int>> pr;

    public:
    AncestorQuerier(Tree* root) {
        int cnt = 0;
        getnodes(root, cnt);
        pr.resize(cnt + 1, vector<int>(20, -1));
        ances(root, NULL);
    }

    void getnodes(Tree* rt, int& cnt) {
        if (rt == NULL) {
            return;
        }
        cnt = cnt + 1;
        getnodes(rt->left, cnt);
        getnodes(rt->right, cnt);
    }

    void ances(Tree* src, Tree* par) {
        if (src == NULL) {
            return;
        }
        pr[src->val][0] = par ? par->val : -1;

        for (int i = 1; i < 20; i++) {
            if (pr[src->val][i - 1] != -1) {
                pr[src->val][i] = pr[pr[src->val][i - 1]][i - 1];
            } else {
                pr[src->val][i] = -1;
            }
        }

        ances(src->left, src);
        ances(src->right, src);
    }

    int getAncestor(int val, int k) {
        cout << val << " " << k << endl;
        if (val == -1 || k == 0) {
            // cout<<k<<" "<<val<<endl;
            return val;
        }
        for (int i = 19; i >= 0; i--) {
            if (k >= (1 << i)) {
                return getAncestor(pr[val][i], k - (1 << i));
            }
        }
        return -1;
    }
};
                    


                        Solution in Java :

import java.util.*;

/**
 * public class Tree {
 *   int val;
 *   Tree left;
 *   Tree right;
 * }
 */
class AncestorQuerier {
    int[][] dp;
    public AncestorQuerier(Tree root) {
        dp = new int[dfs(root) + 5][25];
        for (int i = 0; i < dp.length; i++) Arrays.fill(dp[i], -1);
        dfs(root, root);
    }
    int dfs(Tree tr) {
        if (tr == null)
            return 0;
        return dfs(tr.left) + dfs(tr.right) + 1;
    }
    void dfs(Tree root, Tree par) {
        if (root == null)
            return;
        int vr = root.val, vp = par.val;
        if (root != par) {
            dp[vr][0] = vp;
            for (int i = 1; i < 24; i++) {
                if (dp[vr][i - 1] != -1)
                    dp[vr][i] = dp[dp[vr][i - 1]][i - 1];
            }
        }
        dfs(root.left, root);
        dfs(root.right, root);
    }

    public int getAncestor(int val, int k) {
        int cur = val;
        for (int i = 0; i < 24; i++) {
            if ((k | (1 << i)) == k) {
                cur = dp[cur][i];
            }
            if (cur == -1)
                return -1;
        }
        return cur;
    }
}
                    


                        Solution in Python : 
                            
class AncestorQuerier:
    def __init__(self, root):
        self.p = {}

        def go(r, f):
            if r:
                a = self.p[r.val] = [-1] * 18
                if f:
                    a[0] = f.val
                for i in range(1, 18):
                    if a[i - 1] < 0:
                        break
                    a[i] = self.p[a[i - 1]][i - 1]
                go(r.left, r)
                go(r.right, r)

        go(root, None)

    def getAncestor(self, val, k):
        if val not in self.p:
            return -1
        for i in range(18):
            if (k >> i) & 0x01:
                val = self.p[val][i]
                if val < 0:
                    return -1
        return val
                    


View More Similar Problems

Inserting a Node Into a Sorted Doubly Linked List

Given a reference to the head of a doubly-linked list and an integer ,data , create a new DoublyLinkedListNode object having data value data and insert it at the proper location to maintain the sort. Example head refers to the list 1 <-> 2 <-> 4 - > NULL. data = 3 Return a reference to the new list: 1 <-> 2 <-> 4 - > NULL , Function Description Complete the sortedInsert function

View Solution →

Reverse a doubly linked list

This challenge is part of a tutorial track by MyCodeSchool Given the pointer to the head node of a doubly linked list, reverse the order of the nodes in place. That is, change the next and prev pointers of the nodes so that the direction of the list is reversed. Return a reference to the head node of the reversed list. Note: The head node might be NULL to indicate that the list is empty.

View Solution →

Tree: Preorder Traversal

Complete the preorder function in the editor below, which has 1 parameter: a pointer to the root of a binary tree. It must print the values in the tree's preorder traversal as a single line of space-separated values. Input Format Our test code passes the root node of a binary tree to the preOrder function. Constraints 1 <= Nodes in the tree <= 500 Output Format Print the tree's

View Solution →

Tree: Postorder Traversal

Complete the postorder function in the editor below. It received 1 parameter: a pointer to the root of a binary tree. It must print the values in the tree's postorder traversal as a single line of space-separated values. Input Format Our test code passes the root node of a binary tree to the postorder function. Constraints 1 <= Nodes in the tree <= 500 Output Format Print the

View Solution →

Tree: Inorder Traversal

In this challenge, you are required to implement inorder traversal of a tree. Complete the inorder function in your editor below, which has 1 parameter: a pointer to the root of a binary tree. It must print the values in the tree's inorder traversal as a single line of space-separated values. Input Format Our hidden tester code passes the root node of a binary tree to your $inOrder* func

View Solution →

Tree: Height of a Binary Tree

The height of a binary tree is the number of edges between the tree's root and its furthest leaf. For example, the following binary tree is of height : image Function Description Complete the getHeight or height function in the editor. It must return the height of a binary tree as an integer. getHeight or height has the following parameter(s): root: a reference to the root of a binary

View Solution →