Skip to content

Commit 6a7fa92

Browse files
committed
problem: 0199 binary tree right side view
1 parent 2252fd2 commit 6a7fa92

File tree

2 files changed

+62
-0
lines changed

2 files changed

+62
-0
lines changed
Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
# 0199. Binary Tree Right Side View
2+
3+
Difficulty: medium
4+
Link: https://leetcode.com/problems/binary-tree-right-side-view/
5+
Topics: DFS-BFS
6+
7+
# Clarification
8+
9+
1. Check the inputs and outputs
10+
- INPUT: TreeNode
11+
- OUTPUT: List[int]
12+
13+
# Naive Solution
14+
15+
### Thought Process
16+
17+
1. BFS
18+
2. 只記錄該層最右側的 node
19+
- Implement
20+
21+
```python
22+
# Definition for a binary tree node.
23+
# class TreeNode:
24+
# def __init__(self, val=0, left=None, right=None):
25+
# self.val = val
26+
# self.left = left
27+
# self.right = right
28+
class Solution:
29+
def rightSideView(self, root: Optional[TreeNode]) -> List[int]:
30+
if not root:
31+
return []
32+
result = []
33+
q = collections.deque()
34+
q.append(root)
35+
36+
while q:
37+
lenq = len(q)
38+
for i in range(lenq):
39+
current = q.popleft()
40+
if current.left:
41+
q.append(current.left)
42+
if current.right:
43+
q.append(current.right)
44+
if i == lenq - 1:
45+
result.append(current.val)
46+
return result
47+
```
48+
49+
50+
### Complexity
51+
52+
- Time complexity: O(N)
53+
- Space complexity: O(N)
54+
55+
### Problems & Improvement
56+
57+
- 是否可以直接看右邊的 node 即可
58+
- 需思考這種類型的問題,如果一開始只放 right 的 node 即會出現未考慮到 4 的問題
59+
60+
![Untitled](./Untitled.png)
61+
62+
- 使用 BFS 每一個 level 直接造訪是較 general 的方式
10.2 KB
Loading

0 commit comments

Comments
 (0)