-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathBinaryTreeLevelOrderTraversalII_v1.py
More file actions
58 lines (43 loc) · 1.03 KB
/
BinaryTreeLevelOrderTraversalII_v1.py
File metadata and controls
58 lines (43 loc) · 1.03 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
49
50
51
52
53
54
55
56
57
58
#!/usr/bin/env python
# encoding: utf-8
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
def __repr__(self):
return str(self.val)
class Solution:
# @param {TreeNode} root
# @return {integer[][]}
def levelOrderBottom(self, root):
if not root:
return []
r = []
cur = [root]
while cur:
row = []
next = []
for n in cur:
row.append(n.val)
if n.left:
next.append(n.left)
if n.right:
next.append(n.right)
r = [row] + r
cur = next
return r
if __name__ == '__main__':
s = Solution()
n3 = TreeNode(3)
n9 = TreeNode(9)
n20 = TreeNode(20)
n15 = TreeNode(15)
n7 = TreeNode(7)
root = n3
n3.left = n9
n3.right = n20
n20.left = n15
n20.right = n7
print s.levelOrderBottom(root)