-
Notifications
You must be signed in to change notification settings - Fork 2
/
bfs.py
39 lines (29 loc) · 925 Bytes
/
bfs.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
from typing import 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: TreeNode) -> List[int]:
nodes = [(root, 1)]
curLevel = 1
curVals = []
rightView = []
while nodes:
node, height = nodes.pop(0)
if not node:
continue
if curLevel != height:
rightView.append(curVals[-1])
curVals = []
curLevel = height
curVals.append(node.val)
nodes.append((node.left, height + 1))
nodes.append((node.right, height + 1))
if curVals:
rightView.append(curVals[-1])
return rightView
s = Solution()
s.rightSideView('xxxx')