-
-
Notifications
You must be signed in to change notification settings - Fork 48
Expand file tree
/
Copy path0199-binary-tree-right-side-view.py
More file actions
53 lines (47 loc) · 1.43 KB
/
0199-binary-tree-right-side-view.py
File metadata and controls
53 lines (47 loc) · 1.43 KB
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
# Definition for a binary tree node.
from collections import deque
from typing import List, Optional
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
# BFS
class Solution:
def rightSideView(self, root: Optional[TreeNode]) -> List[int]:
result = []
if root is None:
return result
nextLevel = deque([root,])
while nextLevel:
currLevel = nextLevel
nextLevel = deque()
while currLevel:
node = currLevel.popleft()
if node.left:
nextLevel.append(node.left)
if node.right:
nextLevel.append(node.right)
result.append(node.val)
return result
# DFS
class Solution:
def rightSideView(self, root: Optional[TreeNode]) -> List[int]:
result = []
if not root:
return result
def traverse(node, level):
if len(result) == level:
result.append(node.val)
if node.right:
traverse(node.right, level + 1)
if node.left:
traverse(node.left, level + 1)
traverse(root, 0)
return result
root = TreeNode(1)
root.left = TreeNode(2)
root.right = TreeNode(3)
root.right.right = TreeNode(4)
root.left.right = TreeNode(5)
print(Solution().rightSideView(root))