Skip to content

Commit

Permalink
problem: 0102 binary tree level order traversal
Browse files Browse the repository at this point in the history
  • Loading branch information
cychiu8 committed Feb 25, 2022
1 parent 1374536 commit 0d910f7
Showing 1 changed file with 59 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
# 0102. Binary Tree Level Order Traversal

* Difficulty: medium
* Link: https://leetcode.com/problems/binary-tree-level-order-traversal/
* Topics: DFS-BFS

# Clarification

1. Check the inputs and outputs
- INPUT: Optional[TreeNode]
- OUTPUT: List[List[int]

# Naive Solution

### Thought Process

1. BFS
2. get the nodes from level to level
- Implement

```python
# 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 levelOrder(self, root: Optional[TreeNode]) -> List[List[int]]:

if not root:
return []

result = []
q = collections.deque()
q.append(root)

while q:
lenq = len(q)
r = []
for i in range(lenq):
current = q.popleft()
r.append(current.val)
if current.left:
q.append(current.left)
if current.right:
q.append(current.right)
result.append(r)

return result
```


### Complexity

- Time complexity: $O(N)$
- 遍歷每個節點一次
- Space complexity: $O(N)$
- queue 最大為所有 node 個數

0 comments on commit 0d910f7

Please sign in to comment.