Daily Archives: October 17, 2021

C# || How To Find Cousins In A Binary Tree Using C#

The following is a module with functions which demonstrates how to find the cousins in a binary tree using C#.


1. Is Cousins – 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.

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:

Example 1


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

Example 2:

Example 2


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

Example 3:

Example 3


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


2. Is Cousins – Solution

The following is a solution which demonstrates how to determine if x and y values are cousins in a binary tree.

The idea here is to explore each path, finding the node values that represent x and y.

Once both values are found, save the depth and parent node, and determine if they are cousins

QUICK NOTES:
The highlighted lines are sections of interest to look out for.

The code is heavily commented, so no further insight is necessary. If you have any questions, feel free to leave a comment below.

Once compiled, you should get this as your output for the example cases:


false
true
false