Skip to content
Open

BFS-2 #1574

Show file tree
Hide file tree
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
45 changes: 45 additions & 0 deletions cousins.py
Original file line number Diff line number Diff line change
@@ -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


27 changes: 27 additions & 0 deletions right_sided_binary_tree.py
Original file line number Diff line number Diff line change
@@ -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)