FastPrepTree Node Relationship

Tree Node Relationship

Amazon logoAmazonâ—Ź EasyFULLTIMENEW GRADPHONE SCREEN

Problem statement

You are given an undirected tree with nodes numbered from 0 to n - 1, rooted at node 0. For two queried nodes, classify their relationship.

Return "siblings" if the two nodes have the same parent. Return "cousins" if they are at the same depth but have different parents. Otherwise, return "others".

Function

classifyTreeNodeRelationship(n: int, edges: int[][], nodeA: int, nodeB: int) → String

Examples

Example 1

n = 7edges = [[0,1],[0,2],[1,3],[1,4],[2,5],[2,6]]nodeA = 3nodeB = 4return = "siblings"

Nodes 3 and 4 share parent 1.

Example 2

n = 7edges = [[0,1],[0,2],[1,3],[1,4],[2,5],[2,6]]nodeA = 3nodeB = 5return = "cousins"

Nodes 3 and 5 are both depth 2, but their parents are different.

Example 3

n = 7edges = [[0,1],[0,2],[1,3],[1,4],[2,5],[2,6]]nodeA = 1nodeB = 6return = "others"

The two nodes are at different depths.

Constraints

  • The input graph is a valid tree rooted at node 0. Both queried nodes are valid node ids.

More Amazon problems

See Amazon hiring insights
Saved
public String classifyTreeNodeRelationship(int n, int[][] edges, int nodeA, int nodeB) {
    // write your code here
}
Checking account…