FastPrepClassify Two Nodes as Siblings, Cousins, or Others
Problem · Tree

Classify Two Nodes as Siblings, Cousins, or Others

Learn this problem
MediumAmazon logoAmazonNEW GRADONSITE INTERVIEW
See Amazon hiring insights

Problem statement

A binary tree contains unique integer values. Given the values first and second of two distinct nodes, return:

  • "siblings" if they have the same parent.
  • "cousins" if they have the same depth but different parents.
  • "others" otherwise.

Function

classifyNodeRelationship(root: TreeNode, first: int, second: int) → String

Examples

Example 1

root = [1,2,3,4,5,6,7]first = 4second = 5return = "siblings"

Nodes 4 and 5 share parent 2.

Example 2

root = [1,2,3,4,5,6,7]first = 4second = 6return = "cousins"

Nodes 4 and 6 have equal depth and different parents.

Example 3

root = [1,2,3,4,null,null,7,8]first = 3second = 8return = "others"

One node is at depth one and the other is at depth three.

Constraints

  • The tree contains between 2 and 100000 nodes.
  • Node values are unique and between -10^9 and 10^9.
  • Both target values occur in the tree and are distinct.

More Amazon problems

drafts saved locally
public String classifyNodeRelationship(TreeNode root, int first, int second) {
  // write your code here
}
root[1,2,3,4,5,6,7]
first4
second5
expected"siblings"
checking account