二叉树的层序遍历
解题思路:
广度搜索
1.创建一个新的队列,利用先入先出的特点
2.双层循环,外层循环队列不为空,内层是控制队列的长度
代码:
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
import collections
if __name__ == '__main__':
tree = TreeNode(1)
tree.left=TreeNode(2)
tree.right=TreeNode(3)
sortTree = collections.deque([tree])
result = []
while sortTree:
level = []
for i in range(len(sortTree)):
print(len(sortTree))
cur=sortTree.popleft()
level.append(cur.val)
if cur.left:
sortTree.append(cur.left)
if cur.right:
sortTree.append(cur.right)
result.append(level)
print(result)