Cousins in a Binary Tree
TreesBFS
EasyLeetCode #993
Problem Statement
Given the `root` of a binary tree with unique values, and the values of two different nodes of the tree `x` and `y`, return `true` if the nodes corresponding to the values `x` and `y` in the tree are **cousins**, or `false` otherwise. Two nodes of a binary tree are cousins if they have the same depth with different parents.
Example
Input: root = [1,2,3,4], x = 4, y = 3
Output: false
Algorithm Explanation
We can solve this problem by finding the depth and parent of each of the two nodes, `x` and `y`.
Algorithm Steps
- Find Depth and Parent: We can use a DFS or BFS traversal to find the depth and parent of both `x` and `y`.
- Check Conditions: Once we have the depths and parents, we check if the depths are the same and the parents are different. If both conditions are met, the nodes are cousins.
Start
Starting DFS to find depths and parents.
xDepth: -1
xParent:
yDepth: -1
yParent:
Cousins in a Binary Tree Solution