-
Notifications
You must be signed in to change notification settings - Fork 0
/
199-Binary_Tree_Right_Side_View.py
47 lines (34 loc) · 1.32 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]:
row_collection = collections.defaultdict(list)
def dfs( node, col, row ):
if not node:
return
row_collection[row].append( [ col, node.val ] )
dfs( node.left, col-1, row+1 )
dfs( node.right, col+1, row+1 )
output = []
dfs( root, 0, 0 )
row_collection = dict(sorted( row_collection.items() ))
for row in row_collection:
output.append( row_collection[row][-1][1] )
return output
class SolutionII:
def rightSideView(self, root: Optional[TreeNode]) -> List[int]:
if root is None:
return []
rightside = []
def dfs( node, level ):
if level == len(rightside):
rightside.append(node.val)
for child in [ node.right, node.left ]:
if child:
dfs( child, level+1 )
dfs(root, 0)
return rightside