-
Notifications
You must be signed in to change notification settings - Fork 17
/
Copy pathbinary-tree-level-order-traversal-ii.py
52 lines (37 loc) · 1.16 KB
/
binary-tree-level-order-traversal-ii.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
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
from collections import deque
class Solution:
def levelOrderBottom(self, root: TreeNode) -> List[List[int]]:
if not root:
return []
result = []
queue = [root]
while queue:
old_queue, queue = queue, []
result.append([n.val for n in old_queue])
for node in old_queue:
if node.left:
queue.append(node.left)
if node.right:
queue.append(node.right)
return list(reversed(result))
def levelOrderBottom(self, root):
if not root:
return []
stack = [root]
result = deque()
while stack:
result.appendleft([s.val for s in stack])
old_stack = stack
stack = []
for node in old_stack:
if node.left:
stack.append(node.left)
if node.right:
stack.append(node.right)
return list(result)