题目:从上到下按层打印二叉树,同一层的节点按从左到右的顺序打印,每一层打印到一行。
?示例有两种版本:
1.leetcode版
2.其他版:
?
不同之处在于最后输出样式。
解析:利用宽度/广度优先搜索
关于广度优先搜索,见:https://blog.csdn.net/raphealguo/article/details/7523411
需要一个list作为辅助。
代码:
1.leetcode版本:https://leetcode-cn.com/problems/cong-shang-dao-xia-da-yin-er-cha-shu-ii-lcof/solution/mian-shi-ti-32-ii-cong-shang-dao-xia-da-yin-er-c-5/
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution_bfs:
def leveOrder(self , root):
if not root:return []
res , queue = [] , []
queue.append(root)
while queue:
tmp = []
for _ in range(len(queue)):
node = queue.pop(0)
tmp.append(node.val)
if node.left:queue.append(node.left)
if node.right:queue.append(node.right)
return res
2.其他输出版本:
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def levelOrder(self, root):
if not root:return []
res , queue = [] , []
queue.append(root)
while queue:
new_node = queue.pop(0)
res.append(new_node.val)
if new_node.left:queue.append(root.left)
if new_node.right:queue.append(root.right)
return res
注意:
关于list在循环中进行append操作,不改变进入循环时的元素组成,循环结束后,更新为新的list,例如:
a = [1,2,3,4,5]
for i in range(len(a)):
n = a.pop(0)
print('n = ',n)
a.append(10)
print('a = ',a)
输出:
n = 1
n = 2
n = 3
n = 4
n = 5
a = [10, 10, 10, 10, 10]
|