-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathbinary-tree-level-order-traversal.py
More file actions
37 lines (31 loc) · 1.02 KB
/
binary-tree-level-order-traversal.py
File metadata and controls
37 lines (31 loc) · 1.02 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
# Leetcode 102. Binary Tree Level Order Traversal
#
# Link: https://leetcode.com/problems/binary-tree-level-order-traversal/
# Difficulty: Medium
# 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
# Solution using BSP.
# Complexity:
# O(N) time | where N represent the number of nodes in the tree
# O(M) space | where M represent the number of nodes in one level
class Solution:
def levelOrder(self, root: Optional[TreeNode]) -> List[List[int]]:
result = list()
q = deque()
q.append(root)
while q:
level_size = len(q)
level = list()
for i in range(level_size):
node = q.popleft()
if node:
level.append(node.val)
q.append(node.left)
q.append(node.right)
if level:
result.append(level)
return result