Skip to content

Commit d551167

Browse files
committed
solve : binary tree level order traversal
1 parent 548c334 commit d551167

File tree

1 file changed

+24
-0
lines changed

1 file changed

+24
-0
lines changed
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
# TC : O(n)
2+
# SC : O(n)
3+
class Solution:
4+
def levelOrder(self, root: Optional[TreeNode]) -> List[List[int]]:
5+
q = collections.deque()
6+
res = []
7+
q.append(root)
8+
9+
while q:
10+
level = []
11+
qLen = len(q)
12+
13+
# traverse nodes in each level and append left and right subtree if node is None
14+
for i in range(qLen):
15+
node = q.popleft()
16+
if node:
17+
level.append(node.val)
18+
# append the subtrees of q for the next level in advance
19+
q.append(node.left)
20+
q.append(node.right)
21+
if level:
22+
res.append(level)
23+
24+
return res

0 commit comments

Comments
 (0)