Apple Tree

You are given an undirected tree of n vertices rooted at vertex 1. The tree is represented by a 2D integer array edges of length n - 1, where edges[i] = [u, v] indicates that there is an edge between vertices u and v.

The tree grows "downwards". When an apple is placed at any vertex u, it falls to one of its direct children. It continues falling until it reaches a leaf (a vertex with no children), where it drops to the ground.

You are also given a 2D integer array queries. In each query queries[j] = [x, y], one apple is dropped from vertex x and another from vertex y. Your task is to return an array of the same length as queries, where the answer to the j-th query is the total number of possible pairs of leaves (a, b) such that the first apple drops from leaf a, and the second apple drops from leaf b.

Example 1:

Input: edges = [[1, 2], [3, 4], [5, 3], [3, 2]], queries = [[3, 4], [5, 1], [4, 4], [1, 3]]

Output: [2, 2, 1, 4]

Explanation:

Leaves of the tree are 4 and 5.

  • Query (3, 4): From 3, apples can fall to leaves {4, 5}. From 4, apple falls to {4}. Total pairs = 2 * 1 = 2.
  • Query (5, 1): From 5, leaf {5}. From 1, leaves {4, 5}. Total pairs = 1 * 2 = 2.

Example 2:

Input: edges = [[1, 2], [1, 3]], queries = [[1, 1], [2, 3], [3, 1]]

Output: [4, 1, 2]

Explanation:

Leaves are 2 and 3.

Query (1, 1): Leaves reachable from 1 are {2, 3}. Total pairs = 2 * 2 = 4.

Now Your Turn!

Pick the correct output for the given input

Input: edges = [[1, 2], [1, 3], [1, 4]], queries = [[1, 1]]

Still unsure what the problem is asking ?

Let’s go through a few more examples, step by step, to make it clearer.

Constraints:

  • 1 <= edges.length <= 2 * 105 - 1
  • n == edges.length + 1
  • 1 <= edges[i][0], edges[i][1] <= n
  • 1 <= queries.length <= 2 * 105
  • 1 <= queries[j][0], queries[j][1] <= n

Hints

Frequently Occurring Doubts

Interview Follow-up Questions

Fun Facts

0
class Solution {
public:
vector<long long> appleTree(vector<vector<int>>& edges, vector<vector<int>>& queries) {
}
};
Test Case

Input:

Edges
Queries