Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
51 changes: 51 additions & 0 deletions data_structures/binary_tree/cousins_in_a_Binary_Tree.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
from collections import deque

Check failure on line 1 in data_structures/binary_tree/cousins_in_a_Binary_Tree.py

View workflow job for this annotation

GitHub Actions / ruff

Ruff (N999)

data_structures/binary_tree/cousins_in_a_Binary_Tree.py:1:1: N999 Invalid module name: 'cousins_in_a_Binary_Tree'


class Node:
def __init__(self, val):

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please provide return type hint for the function: __init__. If the function does not return a value, please provide the type hint as: def function() -> None:

Please provide type hint for the parameter: val

self.val = val
self.left = None
self.right = None


def are_cousins(root, x, y):

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

As there is no test file in this pull request nor any test function or class in the file data_structures/binary_tree/cousins_in_a_Binary_Tree.py, please provide doctest for the function are_cousins

Please provide return type hint for the function: are_cousins. If the function does not return a value, please provide the type hint as: def function() -> None:

Please provide type hint for the parameter: root

Please provide descriptive name for the parameter: x

Please provide type hint for the parameter: x

Please provide descriptive name for the parameter: y

Please provide type hint for the parameter: y

if not root:
return False

queue = deque([(root, None)]) # (node, parent)

while queue:
size = len(queue)
x_parent = y_parent = None

for _ in range(size):
node, parent = queue.popleft()

if node.val == x:
x_parent = parent
if node.val == y:
y_parent = parent

if node.left:
queue.append((node.left, node))
if node.right:
queue.append((node.right, node))

# After one level is processed
if x_parent and y_parent:
return x_parent != y_parent # True if different parents
if (x_parent and not y_parent) or (y_parent and not x_parent):
return False # Found one but not the other

return False


# 🔹 Example Usage:
root = Node(1)
root.left = Node(2)
root.right = Node(3)
root.left.left = Node(4)
root.right.right = Node(5)

print("Are 4 and 5 cousins?", are_cousins(root, 4, 5)) # ✅ True
print("Are 2 and 3 cousins?", are_cousins(root, 2, 3)) # ❌ False
Loading