Cousins in Binary Tree
LeetCode 1035 | Difficulty: Easyβ
EasyProblem Descriptionβ
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.
Note that in a binary tree, the root node is at the depth 0, and children of each depth k node are at the depth k + 1.
Example 1:

Input: root = [1,2,3,4], x = 4, y = 3
Output: false
Example 2:

Input: root = [1,2,3,null,4,null,5], x = 5, y = 4
Output: true
Example 3:

Input: root = [1,2,3,null,4], x = 2, y = 3
Output: false
Constraints:
- The number of nodes in the tree is in the range `[2, 100]`.
- `1 <= Node.val <= 100`
- Each node has a **unique** value.
- `x != y`
- `x` and `y` are exist in the tree.
Topics: Tree, Depth-First Search, Breadth-First Search, Binary Tree
Approachβ
Tree DFSβ
Traverse the tree recursively (or with a stack). At each node, decide: what information do I need from the left/right subtrees? Process: go left β go right β combine results. Consider preorder, inorder, or postorder traversal based on when you need to process the node.
Path problems, subtree properties, tree structure manipulation.
Tree BFS (Level-Order)β
Use a queue to process the tree level by level. At each level, process all nodes in the queue, then add their children. Track the level size to know when one level ends and the next begins.
Level-order traversal, level-based aggregation, right/left side view.
Solutionsβ
Solution 1: C# (Best: 156 ms)β
| Metric | Value |
|---|---|
| Runtime | 156 ms |
| Memory | 39 MB |
| Date | 2022-02-12 |
/**
* Definition for a binary tree node.
* public class TreeNode {
* public int val;
* public TreeNode left;
* public TreeNode right;
* public TreeNode(int val=0, TreeNode left=null, TreeNode right=null) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
public class Solution {
private int xDepth = 0;
private int yDepth = 0;
private TreeNode xParent = null;
private TreeNode yParent = null;
public bool IsCousins(TreeNode root, int x, int y) {
CousinDfs(root, x,y, 0, root);
return xDepth == yDepth && xParent != yParent;
}
private void CousinDfs(TreeNode root, int x, int y, int level, TreeNode parent)
{
if(root==null) return ;
if (root.val == x)
{
xDepth=level;
xParent = parent;
}
if (root.val == y)
{
yDepth = level;
yParent = parent;
}
CousinDfs(root.left, x,y, level + 1, root);
CousinDfs(root.right, x,y, level + 1, root);
}
}
Complexity Analysisβ
| Approach | Time | Space |
|---|---|---|
| Tree Traversal | $O(n)$ | $O(h)$ |
Interview Tipsβ
- Start by clarifying edge cases: empty input, single element, all duplicates.
- Consider: "What information do I need from each subtree?" β this defines your recursive return value.