199. Binary Tree Right Side View
2021. 10. 25. 01:56ㆍLeetcode
Description:
Given the root of a binary tree, imagine yourself standing on the right side of it, return the values of the nodes you can see ordered from top to bottom.
# 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
'''
[1] BFS)
idea::
by bfs, there is last element in queue at every step. it will be seen on the right side view
code::
(below)
-T/C: O(n)
-S/C: O(n) # queue
'''
from collections import deque
class Solution:
def rightSideView(self, root: Optional[TreeNode]) -> List[int]:
ans=[]
# when root is null
if not root:
return ans
# init
queue=deque()
queue.append(root)
# bfs
while queue:
size=len(queue)
tmp=[]
for i in range(size):
cur=queue.popleft()
tmp.append(cur.val)
if cur.left:
queue.append(cur.left)
if cur.right:
queue.append(cur.right)
ans.append(tmp[-1])
return ans
'Leetcode' 카테고리의 다른 글
371. Sum of Two Integers (0) | 2021.10.26 |
---|---|
33. Search in Rotated Sorted Array (0) | 2021.10.26 |
103. Binary Tree Zigzag Level Order Traversal (0) | 2021.10.25 |
860. Lemonade Change (0) | 2021.10.24 |
889. Construct Binary Tree from Preorder and Postorder Traversal (0) | 2021.10.23 |