Skip to content

Commit 0d910f7

Browse files
committed
problem: 0102 binary tree level order traversal
1 parent 1374536 commit 0d910f7

File tree

1 file changed

+59
-0
lines changed

1 file changed

+59
-0
lines changed
Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
# 0102. Binary Tree Level Order Traversal
2+
3+
* Difficulty: medium
4+
* Link: https://leetcode.com/problems/binary-tree-level-order-traversal/
5+
* Topics: DFS-BFS
6+
7+
# Clarification
8+
9+
1. Check the inputs and outputs
10+
- INPUT: Optional[TreeNode]
11+
- OUTPUT: List[List[int]
12+
13+
# Naive Solution
14+
15+
### Thought Process
16+
17+
1. BFS
18+
2. get the nodes from level to level
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 levelOrder(self, root: Optional[TreeNode]) -> List[List[int]]:
30+
31+
if not root:
32+
return []
33+
34+
result = []
35+
q = collections.deque()
36+
q.append(root)
37+
38+
while q:
39+
lenq = len(q)
40+
r = []
41+
for i in range(lenq):
42+
current = q.popleft()
43+
r.append(current.val)
44+
if current.left:
45+
q.append(current.left)
46+
if current.right:
47+
q.append(current.right)
48+
result.append(r)
49+
50+
return result
51+
```
52+
53+
54+
### Complexity
55+
56+
- Time complexity: $O(N)$
57+
- 遍歷每個節點一次
58+
- Space complexity: $O(N)$
59+
- queue 最大為所有 node 個數

0 commit comments

Comments
 (0)