-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
从上往下打印二叉树.py
49 lines (43 loc) · 1.12 KB
/
从上往下打印二叉树.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
'''
从上往下打印出二叉树的每个节点,同层节点从左至右打印。
'''
'''
相当于按层遍历, 中间需要队列做转存
'''
# -*- coding:utf-8 -*-
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
# 返回从上到下每个节点值列表,例:[1,2,3]
def PrintFromTopToBottom(self, root):
queue = []
if not root:
return []
result = []
queue.append(root)
while len(queue) > 0:
currentRoot = queue.pop(0)
result.append(currentRoot.val)
if currentRoot.left:
queue.append(currentRoot.left)
if currentRoot.right:
queue.append(currentRoot.right)
return result
pNode1 = TreeNode(8)
pNode2 = TreeNode(6)
pNode3 = TreeNode(10)
pNode4 = TreeNode(5)
pNode5 = TreeNode(7)
pNode6 = TreeNode(9)
pNode7 = TreeNode(11)
pNode1.left = pNode2
pNode1.right = pNode3
pNode2.left = pNode4
pNode2.right = pNode5
pNode3.left = pNode6
pNode3.right = pNode7
S = Solution()
print(S.PrintFromTopToBottom(pNode1))