-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0102_binary_tree_level_traversal.py
More file actions
48 lines (41 loc) · 1.22 KB
/
0102_binary_tree_level_traversal.py
File metadata and controls
48 lines (41 loc) · 1.22 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
38
39
40
41
42
43
44
45
46
47
48
# Definition for a binary tree node.
import collections
from typing import List
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
# We have to save the depth in BFS
# If we face a new depth, extend the list
class IterativeSolution:
def levelOrder(self, root: TreeNode) -> List[List[int]]:
# iterative
if not root:
return []
q = collections.deque([(root, 0)])
l = []
while q:
node, depth = q.popleft()
if not node:
continue
if len(l) == depth:
l.append([])
l[depth].append(node.val)
q.append((node.left, depth + 1))
q.append((node.right, depth + 1))
return l
class RecursiveSolution:
def levelOrder(self, root: TreeNode) -> List[List[int]]:
# recursive
l = []
def helper(root, depth):
if not root:
return
if len(l) == depth:
l.append([])
l[depth].append(root.val)
helper(root.left, depth + 1)
helper(root.right, depth + 1)
helper(root, 0)
return l