From 58718db1dfdbdb90630742a986140946cd2c8c7e Mon Sep 17 00:00:00 2001 From: praxpk <23168694+praxpk@users.noreply.github.com> Date: Fri, 23 Jan 2026 04:23:28 -0500 Subject: [PATCH] BFS-2 --- cousins.py | 45 ++++++++++++++++++++++++++++++++++++++ right_sided_binary_tree.py | 27 +++++++++++++++++++++++ 2 files changed, 72 insertions(+) create mode 100644 cousins.py create mode 100644 right_sided_binary_tree.py diff --git a/cousins.py b/cousins.py new file mode 100644 index 00000000..f6e2c8c5 --- /dev/null +++ b/cousins.py @@ -0,0 +1,45 @@ +""" +time - o(n) +space - o(n) + +we do bfs, we start with the root node and add it to the queue along with the root's current level (0) and parent (none) +for every node we pop, we check if its value is x or y, if it is, we note the level and parent. Once we find all the information +we compare and return true or false +""" +from typing import Optional +from collections import deque + +# 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, None, 0)) + x_level = y_level = None + x_parent = y_parent = None + while q: + node, parent, level = q.popleft() + if node.val == x: + x_level = level + x_parent = parent + if node.val == y: + y_level = level + y_parent = parent + if x_level and y_level and x_parent and y_parent: + if x_level == y_level and x_parent!=y_parent: + return True + else: + return False + if node.left: + q.append((node.left, node, level+1)) + if node.right: + q.append((node.right, node, level+1)) + + return False + + \ No newline at end of file diff --git a/right_sided_binary_tree.py b/right_sided_binary_tree.py new file mode 100644 index 00000000..fd33ed01 --- /dev/null +++ b/right_sided_binary_tree.py @@ -0,0 +1,27 @@ +""" +time = o(n) +space - 0(n) (recursion stack) +we recursively visit every node of tree and check if at each level there is a value in the result array at that index (where level is the index) +if an index = level of the tree is not in result array we just add the right most side of that level into the array, we do this by visiting right side first and then left +""" +from typing import Optional, List +# 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]: + result = [] + self.helper(root, 0, result) + return result + + def helper(self, root, level, result): + if not root: + return + if len(result)==level: + result.append(root.val) + self.helper(root.right, level+1, result) + self.helper(root.left, level+1, result) +