Problem 266
Cousins in Binary Tree
Easy · 10 pts · Tree, Binary Tree, Breadth-First Search
Problem
Two nodes of a binary tree are cousins if they are at the same depth (the same distance from the root) but have different parents. Siblings, which share a parent, are not cousins. You are given a tree with distinct values and two values X and Y that are both in it. Decide whether their nodes are cousins. A single traversal can record the depth and the parent of X and of Y. Then compare: equal depths and different parents means YES.
Input
First line: integer N, the number of tokens. Second line: N tokens describing the tree in level order, where 'null' marks a missing child. Third line: the values X and Y.
Output
Print YES or NO.
Constraints
2 <= number of nodes <= 100; 1 <= value <= 1000; values are distinct; X != Y, both present
Example input
7 1 2 3 4 null null 5 4 5
Example output
YES
Explanation
Node 4 is the left child of 2, and node 5 is the right child of 3. Both are at depth 2, but their parents (2 and 3) differ, so they are cousins: YES.