Leetcode - Binary Tree Right Side View (Python)

preview_player
Показать описание
February 2021 Leetcode Challenge
Leetcode - Binary Tree Right Side View #199
Рекомендации по теме
Комментарии
Автор

I tried to solve it in multiple ways, this is so simple and easy to understand. Thanks a lot.

NvkChaitanya
Автор

I don't understand why we have to do dfs(node.right) first. I did it using node.left first and just updated the values for each level. the last update for each level is the right side view. Also, I don't think we need the if statement if we do it this way. Please let me know if there is a gap in my understanding 🙏.

CEOofTheHood
Автор

I for the life of my could not figure out how to do it recursively lol, so i just went with BFS

if not root:
return []
q = deque([root])

rights = []
while q:
#we need to make sure we get the one all the way on the right
N = len(q)
for i in range(N):
current = q.popleft()
if i == N-1:
rights.append(current.val)
if current.left:
q.append(current.left)
if current.right:
q.append(current.right)
return rights

janmichaelaustria
Автор

Hello, I'm preparing for coding interview w/ Neetcode pro.
Can you check wrong part of this code?
I think it's close, but it's not working :((



from collections import deque

class Solution(object):
def rightSideView(self, root):
"""
:type root: TreeNode
:rtype: List[int]
"""
res = []
queue = deque([root])

if(not root):
return None

curr = root
while queue:
for i in range(len(queue)):
curr = queue.popleft()

if(curr.left):
queue.append(curr.left)
elif(curr.right):
queue.append(curr.right)
res.append(curr.val)

return res

jihowoo
welcome to shbcf.ru