-
Notifications
You must be signed in to change notification settings - Fork 0
/
102-Binary_Tree_Level_Order_Traversal.py
59 lines (46 loc) · 1.58 KB
/
102-Binary_Tree_Level_Order_Traversal.py
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
49
50
51
52
53
54
55
56
57
58
59
# 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
## Sol: DFS
# Using recursion, keep track of depth and use it as index for the List List array.
## Time: O(N)
## Space: O(N)
class SolutionI:
def levelOrder(self, root: TreeNode) -> List[List[int]]:
if root is None: return []
ansL = []
ansL.append( [] )
self.NextLevel( root, 0, ansL )
return ansL
def NextLevel( self, root, Level, ansL ):
if root is None: return
ansL[Level].append( root.val )
if root.left is not None or root.right is not None:
if len(ansL) < Level + 2:
ansL.append([])
self.NextLevel( root.left, Level+1, ansL )
self.NextLevel( root.right, Level+1, ansL )
## Sol: BFS
## Time: O(N)
## Space: O(N)
class SolutionII:
def levelOrder(self, root: TreeNode) -> List[List[int]]:
next_queue = []
Level = []
Ans = []
queue = [root]
while queue:
for root in queue:
if root is None: continue
Level.append( root.val )
next_queue.append( root.left )
next_queue.append( root.right )
queue = next_queue
next_queue = []
if not len(Level): continue
Ans.append( Level )
Level = []
return Ans