Skip to content
Open
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
37 changes: 37 additions & 0 deletions Problem1.py
Original file line number Diff line number Diff line change
@@ -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

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