From 5597659a242b833d28a747f2295758cf6db9505b Mon Sep 17 00:00:00 2001 From: pranjay01 Date: Sun, 15 Mar 2026 14:01:38 -0700 Subject: [PATCH] Done BFS 2 --- Problem1.py | 37 +++++++++++++++++++++++++++++++++++++ Problem2.py | 46 ++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 83 insertions(+) create mode 100644 Problem1.py create mode 100644 Problem2.py diff --git a/Problem1.py b/Problem1.py new file mode 100644 index 00000000..20082737 --- /dev/null +++ b/Problem1.py @@ -0,0 +1,37 @@ +#Binary Tree Right Side View + +# 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 + +# Time complexity -> On +# Space complexity -> On +# Logic -> Use levelOrderTraversal to maintaing all the elements of the same level in a same level and do it in such a way + # that always rightmost is enetered 1st then the 1st element will always be the 1 that will be seen from the right + +from collections import deque +class Solution: + def rightSideView(self, root: Optional[TreeNode]) -> List[int]: + + result = [] + levelQueue = deque() + levelQueue.append(root) + + while len(levelQueue) > 0: + itemsInCurrentLevel = len(levelQueue) + + for i in range(itemsInCurrentLevel): + node = levelQueue.popleft() + if i == 0: + result.append(node.val) + if node.right: + levelQueue.append(node.right) + + if node.left: + levelQueue.append(node.left) + + return result + diff --git a/Problem2.py b/Problem2.py new file mode 100644 index 00000000..6c247efc --- /dev/null +++ b/Problem2.py @@ -0,0 +1,46 @@ +#Cousins in Binary 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 + +# Time -> On +# Space -> On + +from collections import deque + +class Solution: + def isCousins(self, root: Optional[TreeNode], x: int, y: int) -> bool: + # get the elements at depth A usign elvel order traversal, if both elements at that level + # but have different parents then they are cousins else not + + levelQueue = deque() + + levelQueue.append(root) + foundCousingX = False + foundCousingY = False + while levelQueue: + totalItemsInCurrentLevel = len(levelQueue) + for i in range(totalItemsInCurrentLevel): + node = levelQueue.popleft() + + # check for same parent + if node.left and node.right: + vals = {node.left.val, node.right.val} + if x in vals and y in vals: + return False + # check if found val then update the flag + for child in filter(None, [node.left, node.right]): + foundCousingX = child.val == x or foundCousingX + foundCousingY = child.val == y or foundCousingY + levelQueue.append(child) + + # if in the last level found both and reached here means sibling + if foundCousingX and foundCousingY: + return True + # if in the last level found only 1 then not sibling + if foundCousingX or foundCousingY: + return False \ No newline at end of file