-
Notifications
You must be signed in to change notification settings - Fork 0
/
102_binary_tree_level_order_traversal.py
80 lines (72 loc) · 2.04 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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
#!/usr/bin/python
# -*- coding: utf-8 -*-
#author : zhangdawang
#data:2017-4-26
#difficulty degree:
#problem: 102_binary_tree_level_order_traversal
#time_complecity:
#space_complecity:
#beats:
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
def CreateTree(self, tree, nums, i):
if i >= len(nums) // 2:
return
if nums[2 * i] != 0:
tree.left = TreeNode(nums[2 * i])
self.CreateTree(tree.left, nums, 2*i)
if nums[2 * i + 1] != 0:
tree.right = TreeNode(nums[2 * i + 1])
self.CreateTree(tree.right, nums, 2*i + 1)
def GenerateTree(self, nums):
root = TreeNode(nums[1])
self.CreateTree(root, nums, 1)
return root
class Solution(object):
#层序遍历
def isSymmetric(self, root):
res = []
queue = [root]
while queue:
temp = []
queue.append("#")
while True:
q = queue.pop(0)
if q =="#":
break
if q == None:
continue
print(q.val)
temp.append(q.val)
queue.append(q.left)
queue.append(q.right)
res.append(temp)
res.pop()
return res
def levelOrder2(self, root):
if not root: return []
queue = collections.deque([root, "#"])
res, level = [], []
while queue:
node = queue.popleft()
if node == "#":
res.append(level)
if queue:
queue.append("#")
level = []
else:
level.append(node.val)
if node.left:
queue.append(node.left)
if node.right:
queue.append(node.right)
return res
nums = [0,1,2,2,0,4,4,3]
a = TreeNode(1)
root = a.GenerateTree(nums)
solute = Solution()
res = solute.isSymmetric(root)
print(res)