Problem · Tree
Tree Node Relationship
Learn this problemProblem 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) → StringExamples
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
- Resolve Task DependenciesONSITE INTERVIEW · Seen Jul 2026
- Shortest Distance on a Circular Bus RouteOA · Seen Jul 2026
- Longest Increasing Subsequence With Bounded Adjacent DifferenceONSITE INTERVIEW · Seen Jul 2026
- Search in a Rotated Sorted ArrayONSITE INTERVIEW · Seen Jul 2026
- Sliding Window MaximumONSITE INTERVIEW · Seen Jul 2026
- Merge IntervalsOA · Seen Jul 2026
- Sort Bug Report FrequenciesOA · Seen Jul 2026
- Drone Delivery RouteOA · Seen Jul 2026