Ctrl K

Same Depth, Different Parents

Easy
You are given a binary tree root whose node values are all distinct, and two different values a and b that are both present in the tree. The root is at depth 0, and the children of a node at depth k are at depth k + 1. Two nodes are cousins when they are at the same depth but have different parents. Return True if the nodes holding a and b are cousins, and False otherwise.
Example 1
root=tree_node([7, 3, 9, 5, None, None, 8]), a=5, b=8 → True

5 is a child of 3 and 8 is a child of 9. Both sit at depth 2 with different parents, so the answer is True.

Example 2
root=tree_node([7, 3, 9, 5, 6]), a=5, b=6 → False

5 and 6 are at the same depth but share the parent 3: they are siblings, not cousins.

Example 3
root=tree_node([7, 3, 9, 5]), a=5, b=9 → False

5 is at depth 2 while 9 is at depth 1.

Constraints
  • The tree has between 2 and 100 nodes
  • 1 ≤ Node.val ≤ 100, all values are distinct
  • a ≠ b, and both values are in the tree
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsIdentical Trees EasyMirror-Image Tree EasyTree Height EasyNearest Leaf Depth EasyLeaf Path With a Given Total Easy
loading Python…
Input
root=tree_node([7, 3, 9, 5, None, None, 8]), a=5, b=8
Expected
True

Run checks the first 3 tests in your browser. Submit checks all 56 tests on the server, hidden ones included.