Problem · Tree
Classify Two Nodes as Siblings, Cousins, or Others
Learn this problemProblem 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) → StringExamples
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
2and100000nodes. - Node values are unique and between
-10^9and10^9. - Both target values occur in the tree and are distinct.