We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
There was an error while loading. Please reload this page.
1 parent 548c334 commit d551167Copy full SHA for d551167
binary-tree-level-order-traversal/samthekorean.py
@@ -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