From 966397c9618388c346bd6ba0ae54f77571380c8f Mon Sep 17 00:00:00 2001 From: Shinjanee Gupta Date: Wed, 4 Mar 2026 18:08:18 -0800 Subject: [PATCH] BFS-2 --- Cousins.py | 50 ++++++++++++++++++++++++++++++++++++++++++++++++++ RightView.py | 39 +++++++++++++++++++++++++++++++++++++++ 2 files changed, 89 insertions(+) create mode 100644 Cousins.py create mode 100644 RightView.py diff --git a/Cousins.py b/Cousins.py new file mode 100644 index 00000000..5865a974 --- /dev/null +++ b/Cousins.py @@ -0,0 +1,50 @@ +# Time Complexity : O(n) +# Space Complexity : O(n) +# Did this code successfully run on Leetcode : Yes +# Any problem you faced while coding this : No +# Approach : Do a level order traversal using a queue, checking each level for x and y. +# If they are siblings (same parent), return false immediately. +# If both found on the same level but not siblings, return true, otherwise false. + +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right +class Solution: + def isCousins(self, root: Optional[TreeNode], x: int, y: int) -> bool: + q = deque() + q.append(root) + + x_found, y_found = False, False + + while q: + size = len(q) + + for _ in range(size): + curr = q.popleft() + + if curr.left and curr.right: + # siblings - same parent + if curr.left.val == x and curr.right.val == y: + return False + if curr.right.val == x and curr.left.val == y: + return False + + if curr.val == x: + x_found = True + if curr.val == y: + y_found = True + + if curr.left: + q.append(curr.left) + if curr.right: + q.append(curr.right) + + if x_found and y_found: + return True # same leval + if x_found or y_found: + return False # different level - not cousins + + return True \ No newline at end of file diff --git a/RightView.py b/RightView.py new file mode 100644 index 00000000..643bed0f --- /dev/null +++ b/RightView.py @@ -0,0 +1,39 @@ +# Time Complexity : O(n) +# Space Complexity : O(n) +# Did this code successfully run on Leetcode : Yes +# Any problem you faced while coding this : No +# Approach : Do level order traversal using a queue. +# For each level, we add the last node's value to the result which gives the right side view of the tree. +# For each level, if we add the first node's value to the resul, then it will give the left side view of the tree. + +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right +class Solution: + def rightSideView(self, root: Optional[TreeNode]) -> List[int]: + res = [] + + if root is None: + return res + + q = deque() + q.append(root) + + while q: + size = len(q) + + for i in range(size): + curr = q.popleft() + + if i == size - 1: + res.append(curr.val) + + if curr.left: + q.append(curr.left) + if curr.right: + q.append(curr.right) + return res + \ No newline at end of file