From 64b02b297f9fe9db00fdd3213c81a0bb320dc247 Mon Sep 17 00:00:00 2001 From: Divyansh Raj Soni <110761086+DivyanshRajSoni@users.noreply.github.com> Date: Sun, 5 Oct 2025 15:42:28 +0530 Subject: [PATCH 1/2] Create cousins_in_a_Binary_Tree.py --- .../binary_tree/cousins_in_a_Binary_Tree.py | 49 +++++++++++++++++++ 1 file changed, 49 insertions(+) create mode 100644 data_structures/binary_tree/cousins_in_a_Binary_Tree.py diff --git a/data_structures/binary_tree/cousins_in_a_Binary_Tree.py b/data_structures/binary_tree/cousins_in_a_Binary_Tree.py new file mode 100644 index 000000000000..d7d0287ef078 --- /dev/null +++ b/data_structures/binary_tree/cousins_in_a_Binary_Tree.py @@ -0,0 +1,49 @@ +from collections import deque + +class Node: + def __init__(self, val): + self.val = val + self.left = None + self.right = None + +def are_cousins(root, x, 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 From 5fbd9f8372d5b80ab2bdb212bd1ab02fb2a01eb9 Mon Sep 17 00:00:00 2001 From: "pre-commit-ci[bot]" <66853113+pre-commit-ci[bot]@users.noreply.github.com> Date: Sun, 5 Oct 2025 10:14:37 +0000 Subject: [PATCH 2/2] [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci --- data_structures/binary_tree/cousins_in_a_Binary_Tree.py | 2 ++ 1 file changed, 2 insertions(+) diff --git a/data_structures/binary_tree/cousins_in_a_Binary_Tree.py b/data_structures/binary_tree/cousins_in_a_Binary_Tree.py index d7d0287ef078..2ffbc21c0aa3 100644 --- a/data_structures/binary_tree/cousins_in_a_Binary_Tree.py +++ b/data_structures/binary_tree/cousins_in_a_Binary_Tree.py @@ -1,11 +1,13 @@ from collections import deque + class Node: def __init__(self, val): self.val = val self.left = None self.right = None + def are_cousins(root, x, y): if not root: return False