-
Notifications
You must be signed in to change notification settings - Fork 0
/
199-binary-tree-right-side-view.py
47 lines (37 loc) · 1.29 KB
/
199-binary-tree-right-side-view.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
# 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]:
# return empty list if root is empty
if not root:
return []
# run a DFS on the tree, adding only the rightmost node at each layer to the result
ans = []
# create queue
queue = deque([root])
# track width of each layer
width = len(queue)
i = 0
# DFS as normal apart from tracking and adding rightmost node
while queue:
node = queue.popleft()
# add children to queue
if node.left:
queue.append(node.left)
if node.right:
queue.append(node.right)
# if end of layer, i.e. rightmost node, add to result and update width
if i+1 == width:
# add value to result
ans.append(node.val)
# update width
width = len(queue)
i = 0
else:
# otherwise update index
i += 1
return ans