-
Notifications
You must be signed in to change notification settings - Fork 17
/
Copy pathbinary-tree-right-side-view.py
55 lines (37 loc) · 1.15 KB
/
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
48
49
50
51
52
53
54
55
from typing import List, Optional
# 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]:
output: List[int] = []
def dfs(node: TreeNode, level: int) -> None:
if level + 1 > len(output):
output.append(node.val)
if node.right:
dfs(node.right, level + 1)
if node.left:
dfs(node.left, level + 1)
if not root:
return []
dfs(root, 0)
return output
class Solution1:
def rightSideView(self, root):
result = []
if not root:
return result
stack = [root]
while stack:
old_stack = stack
stack = []
result.append(old_stack[-1].val)
for node in old_stack:
if node.left:
stack.append(node.left)
if node.right:
stack.append(node.right)
return result